When I was watching Teacher Gao’s video recently, I found a knowledge point that I didn’t quite understand. The code is as follows:
public class Test065 {
public static void main(String[] args){
Date d = new Date();//得到当前时间的毫秒数
System.out.println(d);
Dog a = new Dog();
System.out.println(a);
}
}
class Dog{
int age;
}
The output results are as follows:
Thu Jun 15 19:43:29 CST 2017
com.test065.Dog@33909752
It also prints an object. Why does the Date class object output the current time, while the self-built object outputs the hash code?
Xiaomengxin asks friends to clarify their doubts, I am very impressed!
The Println method will call the toString method of the output object. If the object does not define the toString method, it will follow the inheritance chain to find the parent class.
Date has a toString method defined, so the output is formatted attribute information.
The custom Dog class does not have a toString method, so the toString method of the parent class is used, which is Object's
When printing an object, the return value of its toString method will be printed. Date overrides the toString method. If Dog does not override toString, it will call the toString method of the parent class Object
The Date class overrides toString() in the Object parent class, but your own class does not. . . Take a look at the source code of Date class
The toString method has been rewritten, you can check it out in the source code yourself.