为什么参数方法中的行定义方法匿名内部类工作?

时间:2016-05-20 05:14:18

标签: java inner-classes anonymous-class anonymous-methods anonymous-inner-class

InterfaceInAbstractClass.java

public abstract class InterfaceInAbstractClass {

    public interface Inter{

        void interface_method();

    }

    public  void interface_abstract_class_method(Inter in){

    }

}

InterfaceInAbstractClassImplementer.java

public class InterfaceInAbstractClassImplementer extends InterfaceInAbstractClass{

    public static void main(String[] args){

//      InterfaceInAbstractClass.Inter abcd = new InterfaceInAbstractClass.Inter() {
//          
//          @Override
//          public void interface_method() {
//              // TODO Auto-generated method stub
//              System.out.println("An interface can be implemented ");
//          }
//      };
        System.out.println("An interface can be implemented ");
        InterfaceInAbstractClassImplementer abc = new InterfaceInAbstractClassImplementer();
        abc.interface_abstract_class_method(new Inter() {

            @Override
            public void interface_method() {
                // TODO Auto-generated method stub
                System.out.println("An interface can be implemented within a class");
            }
        });     
    }
}

为什么System.out.println("一个接口可以在一个类中实现");没有印刷?

1 个答案:

答案 0 :(得分:1)

对您的实现者类进行一些小调整以调用接口函数

public class InterfaceInAbstractClassImplementer extends InterfaceInAbstractClass{

    public static void main(String[] args){

        System.out.println("An interface can be implemented ");
        InterfaceInAbstractClassImplementer abc = new InterfaceInAbstractClassImplementer();
        Inter inter = new Inter() {

            @Override
            public void interface_method() {
                // TODO Auto-generated method stub
                System.out.println("An interface can be implemented within a class");
            }
        };
        abc.interface_abstract_class_method(inter);
    }

    public void interface_abstract_class_method(Inter inter) {
        inter.interface_method();
    }
}

输出:

An interface can be implemented
An interface can be implemented within a class