Tag: Object String Hashcode
A: First look at Demo1
<strong><span style= "FONT-SIZE:18PX;" >public class Dog1{dog1 () {}public static void main (string[] args) {Dog1 d = new Dog1 (); System.out.println (d);}} </span></strong>
Output Result:
[Email protected]
How often do we see the output of an object like this? But have you thought about why you're outputting this result?
To understand this output, you need to know the object class, theobject class is the base class for all Java classes.
The class definition above is actually equivalent to
<strong><span style= "FONT-SIZE:18PX;" >public class Dog1<span style= "color: #ff0000;" > Extends object{</span></span></strong>
<strong><span style= "FONT-SIZE:18PX;" There is a ToString () method in the >object class </span></strong>
<strong><span style= "FONT-SIZE:18PX;" > Its implementation code is:</span></strong>
<strong><span style= "FONT-SIZE:18PX;" > <span style= "color: #ff0000;" >public String toString () {<span style= "White-space:pre" ></span> return GetClass (). GetName () + "@" + Inte Ger.tohexstring (Hashcode ()); }</span></span></strong>
System.out.println (d);
Equivalent to System.out.println ("" +d);
Equivalent to System.out.println ("" +d.tostring ());
Any object that is spliced with a string converts the object into a string type, which is equivalent to the ToString method of the calling object. This will call the ToString () method of the parent class
Second: See 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);}
To see the results of the output:
I am a dog
Why is it?
Because DOG2 overrides the ToString () method of the parent class object. It will call its own ToString method.
The recommended class is best to rewrite the ToString () method of object.
Java Basics: The ToString method of Object