Vanjul
Vanjul

Reputation: 45

Ability to instantiate an interface

I have the impression that it is possible to instantiate an interface:

interface TestA { 
   String toString(); 
}

public class Test {
    public static void main(String[] args) {

       System.out.println(new TestA() {
          public String toString() { 
              return "test"; 
          }
       });
    }
 }

This prints "test". Why? The class doesn't implement the interface.

Also it creates an instance of it using new TestA() but I read interfaces cannot be instantiated.

Can someone please explain why it prints successfully ?

Upvotes: 0

Views: 90

Answers (1)

Vic Seedoubleyew
Vic Seedoubleyew

Reputation: 10536

What is going on

What you are doing here is creating an anonymous class, and instantiating it. So your object's type is not TestA, but actually the type of the anonymous class.

TestA myObject = new TestA(){ ... }

is a shortcut for :

class ClassA implements TestA { ... }
TestA myObject = new ClassA();

In this example, although the type of the reference myObject is TestA, the type of the referenced object is ClassA, which implements TestA.

You can read about anonymous classes in the Java Tutorial here.

The last step of "what is going on", is your call of System.out.println on the created object, which as a consequence calls its toString() method.

So to break up all the steps that are happening, your code is equivalent to :

public class Test {

   public static void main(String[] args){

      class ClassA implements TestA {

        public String toString(){
            return "test";
        }
      }
      TestA myObject = new ClassA();
      String myString = myObject.toString();
      System.out.println(myString);
   }
}

Answer to your precise questions

So to answer your precise questions :

  • indeed, your class Test doesn't implement the interface, the anonymous class does. It does both because it is declared as implementing it, and because it correctly implements the abstract method toString
  • indeed, interfaces cannot be instantiated. In this case, you are not instantiating the interface, but the anonymous class that you define as implementing the interface.

If you would like to check that second point, you can try removing the body of your anonymous class definition. It won't compile :

System.out.println(new TestA()); // Compile error

Upvotes: 6

Related Questions