Search code examples
javainner-classesanonymous-classanonymous-methodsanonymous-inner-class

Why does the line inside method of argument defined method anonymous inner class work?


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");
            }
        });     
    }
}

Why does the System.out.println("An interface can be implemented within a class"); doesn't get printed?


Solution

  • A small tweak to your implementer class to call the interface function

    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();
        }
    }
    

    Output:

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