3

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?

  • https://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java – Reimeus Aug 17 '17 at 23:18
  • It doesn't output an object of class Test. Your output is missing a `@` *(at least for Oracle JDK)*, and should be `Test$1@6d06d69c`, which is [**anonymous class**](https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html) number `1` of class `Test`, with hash code `6d06d69c`. – Andreas Aug 17 '17 at 23:21

2 Answers2

4

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.

bhspencer
  • 13,086
  • 5
  • 35
  • 44
0

Just to expound on @bhspencer's answer in the case when A has defined methods:

An interface has no constructor and cannot be instantiated directly. it can however be implemented inline. Consider the following implementation of A:

public class B implements A {
   @Override
   public void printMyName() {
       System.out.println("B");
   }
}

And code that instantiates an instance of B:

public A a = new B();

This is equivalent syntax to an anonymous inline implementation of interface A that reads as follows:

public A a = new A() {
     @Override
     public void printMyName() {
         System.out.println("B");
     }
}

Java allows us to implement interfaces inline and instantiate them without creating an explicit separate class.

Master_Yoda
  • 1,092
  • 2
  • 10
  • 18