Home  >  Q&A  >  body text

In Gao Qi's Java video code, why does the time print out using a new object created using the Date class, but the hash code address prints out using a self-created object?

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!

巴扎黑巴扎黑2646 days ago908

reply all(4)I'll reply

  • 欧阳克

    欧阳克2017-06-23 09:16:34

    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

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-23 09:16:34

    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

    reply
    0
  • typecho

    typecho2017-06-23 09:16:34

    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

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-23 09:16:34

    The toString method has been rewritten, you can check it out in the source code yourself.

    reply
    0
  • Cancelreply