-2

Interface :

public interface MyFirstInterface {
    void myFirstAbstractMethod();
    default void myDefaultMethod() {
        System.out.println("Hi I am default method in Interface.");
    }
}

Class:

public class MyFirstClass{
    public static void main(String[] args) {
    MyFirstInterface myFirstInterface = new MyFirstInterface() {
        @Override
        public void myMethod() {
            System.out.println("Main class : "+this.getClass());
        }

    };

    myFirstInterface.myMethod();
    myFirstInterface.defaultMethod();

    }
}

Now we know we are instantiating a anonymous class, what I want to know is Why would anyone use it? What is the advantage or disadvantage of doing it?

Himanshu Gupta
  • 77
  • 1
  • 1
  • 9

1 Answers1

0

It is not a constructor. It is a method a() declaration with the return type A.

Also, we can instantiate an interface using an anonymous class. Runnable for example:

Runnable r = new Runnable() {
   @Override 
   public void run() { ... }
};

Runnable r = () -> { ... }
Sergei Rybalkin
  • 3,337
  • 1
  • 14
  • 27