Nid3248971
Nid3248971

Reputation: 9

If interface cannot have a constructor, what happens here?

need some help on this, If interface cannot have a constructor, what happens here?

interface A{
     String toString(); 
}

public class B{
    public static void main(String[] args) {
        System.out.println(new A() {
           public String toString() { 
              return "what happens here!!"; 
           }
     });
    }
}

Upvotes: 0

Views: 118

Answers (2)

Kayaman
Kayaman

Reputation: 73558

An instance of an anonymous class implementing A is created.

This has very little to do with constructors, except that the default no-arg constructor will be called, and the toString() method is already defined in the Object class, so the interface is superfluous.

Upvotes: 10

Marko Topolnik
Marko Topolnik

Reputation: 200168

public static void main(String[] args) {
  System.out.println(new A() {
     public String toString() { return "what happens here!!"; }
  });
}

can be more explicitly rewritten as follows:

public static void main(String[] args) {
   class ImplA() extends Object implements A {
     public ImplA() { super(); }
     public String toString() { return "what happens here!!"; }
   }
   System.out.println(new ImplA());
}

From the above you can understand the following:

  • the local class ImplA is a subclass of Object and also implements A;
  • Object has a nullary constructor;
  • ImplA defines a nullary constructor, which delegates to Object's nullary constructor;
  • the constructor thus declared is called when writing new ImplA();

Your version of code just employs Java's syntactic sugar which lets you combine local class declaration with class instantiation into a single expression.

Upvotes: 3

Related Questions