Is it possible to create an object for an interface? If yes, how is it done? According to my view the following code says that we can:
Is it possible to creating object for an interface?
No. The code you've shown creates an object from an anonymous class, which implements the interface. Under the covers, the JVM actually creates a class implementing the interface, and then creates an instance of that class.
The "anonymous" class generated will actually have a name, based on the name of the class in which this code appears, for instance YourClass$1
or similar. E.g.:
public class AnonymousName {
public static final void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
}
};
System.out.println(r.getClass().getName());
}
}
...outputs
AnonymousName$1
(At least on Oracle's JVM; I don't know if the naming convention is in the JLS or if it's JVM-specific behavior.)