Java basics: The toString method of the Object
I. First, check Demo1.
public class Dog1{Dog1(){}public static void main(String[] args) {Dog1 d = new Dog1();System.out.println(d);}}
Output result:
Dog1 @ 77aaf64d
What is the output result of an object? But have you ever wondered why this result is output?
To understand this output, you need to understand the Object class. The Object class is the base class of all java classes.
That is, the class definition above is equivalent
public class Dog1 extends Object{
The Object class has a toString () method.
Its implementation code is:
public String toString() { return getClass().getName() + @ + Integer.toHexString(hashCode()); }
System. out. println (d );
// Equivalent to System. out. println (+ d );
// Equivalent to System. out. println (+ d. toString (); www.bkjia.com
// Any object and String concatenation will convert the object to the string type, which is equivalent to calling the toString method of the object. The toString () method of the parent class will be called here
Ii. Check Demo2 again.
public class Dog2{Dog2(){} public String toString() { return i am a dog; }public static void main(String[] args) {Dog2 d = new Dog2();System.out.println(d);}
Let's see the output:
I am a dog
Why?
Because Dog2 overrides the Override toString () method of the parent class Object. You will call your own toString method.
It is recommended that you rewrite the toString () method of the Object.