Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this interface being instantiated? (Java 8)

Tags:

java

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?

like image 730
avinashakumar24 Avatar asked Mar 17 '26 00:03

avinashakumar24


1 Answers

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.

like image 81
bhspencer Avatar answered Mar 19 '26 14:03

bhspencer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!