As far as I know, interfaces cannot be instantiated directly. However, whenever I compile the following code:
interface A {};
public class Test {
public static void main(String[] args){
A a = new A() {};
system.out.println(a);
it outputs the toString() of an object of class Test:
Test$16d06d69c
And when I change
A a = new A() {};
to
A a = new A();
it doesn't compile. Why is this happening? Is the interface being instantiated, or is something else happening behind the scenes?
You are defining a new anonymous inline class that implements interface A with the statement:
A a = new A() {};
And in the same statement you are constructing a new instance of your new anonymous class definition.
So no you are not instantiating an interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With