About Lesson
In Java, you cannot directly create an instance of an interface because interfaces are abstract types that cannot be instantiated. However, starting from Java 9, you can create an anonymous class instance using an interface’s new
keyword and implement its methods on the spot.
public interface MyInterface {
void myMethod();
}
public class Main {
public static void main(String[] args) {
// Creating an object of the interface using an anonymous class
MyInterface myInterface = new MyInterface() {
@Override
public void myMethod() {
System.out.println("Implementing myMethod() in an anonymous class.");
}
};
// Calling the method
myInterface.myMethod(); // Output: Implementing myMethod() in an anonymous class.
}
}
It allows you to define and implement interface methods without explicitly creating a separate class.
Anonymous classes are not reusable, meaning you cannot create multiple instances with the same implementation.