Can anybody explain the working of following code…?
interface myInterface{}
public class Main {
public static void main(String[] args) {
System.out.println(new myInterface(){public String toString(){return "myInterfacetoString";}});
System.out.println(new myInterface(){public String myFunction(){return "myInterfacemyFunction";}});
}
}
Output is…
myInterfacetoString
primitivedemo.Main$2@9304b1
All answers saying that myInterface in println() statement is anonymous class. But as I already declared it as an interface, why does it allow me to create anonymous class of same name….?
again…if these are anonymous classes then class main should allow me to give any name to these anonymous classes..But if try to do so..I’m getting compilation error
When you print out an object, it will call the toString() method. In the first statement, you create new object and also override method called toString. Therefore, this toString() method is called when object is printed.
In the second statement, you also create an object but you don’t override the toString() method so that it will use the toString() method of the Object class.
For the new question, this link has a good explanation for your understanding:
Anonymous Classes
Here is a copy of the explanation:
This expression instantiates a new object from an unnamed and previously undefined class, which automatically extends the class named className, and which cannot explicitly implement any interfaces. The body of the new class is given by classBody.
The result of executing this expression is that a new class that extends className is defined, a new object of the new class is instantiated, and the expression is replaced by a reference to the new object.
This expression instantiates a new object from an unnamed and previously undefined class, which automatically implements the interface named interfaceName, and automatically extends the class named Object. The class can explicitly implement one, and only one interface, and cannot extend any class other than Object. Once again, the body of the new class is given by classBody.
Is it clear for you now?