When you print an object, it calls the toString () method. In the first statement, you create a new object, as well as an override method toString. Therefore, this toString () method is called when the object is printed.
In the second expression, you also create an object, but you do not override the toString () method to use the toString () method of the Object class.
For a new question, this link has a good explanation for your understanding: Anonymous classes
Here is a copy of the explanation:
new className(optional argument list){classBody}
This expression creates 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 defined by the Body class.
The result of this expression is that a new class is defined that extends className , an instance of a new object of the new class is created, and the expression is replaced with a reference to the new object .
new interfaceName(){classBody}
This expression creates a new object from an unnamed and previously undefined class that automatically implements an interface named interfaceName and automatically extends a class called Object . A 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 the Body class.
Is this clear to you now?
vodkhang
source share