Reputation: 9
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
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
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:
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;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