Why Date class object prints the date/time/.. Where as if we print anyother object it gives address?

时间:2017-06-15 09:27:03

标签: java class date object

Consider the Following code snippet:

    //Assume the import statements


     Date ob=new Date();
    System.out.println(ob);

    //Where As

    DateFormat df=DateFormat.getDateInstance();//Just as an Example
    System.out.println(df);

Output is as follows:

1.Thu Jun 15 14:53:03 IST 2017

2.java.text.SimpleDateFormat@ce9bf0a5( i know this is hashcode)

Question is : Why the peculiarity with Date ob?

3 个答案:

答案 0 :(得分:2)

When you try to print an object, it calls toString() method of the corresponding class. If a class doesn't override toString(), it calls the Object class version of toString(). Now, let's have a look at the javadoc of Date class and toString() method:

Converts this Date object to a String of the form:

dow mon dd hh:mm:ss zzz yyyy

So, it overrides toString() and hence, we see the String output.

Now, DateFormat class (javadoc here) lists toString() as one of the methods inherited from class java.lang.Object (meaning it doesn't override toSting()) and hence, Object class version of toString() is called, resulting in hash of the object getting printed.

Here's the documentation of toString() method of Object class, this is what it says:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

答案 1 :(得分:0)

When we print the object then its toString() method is called.

public String toString() method is present in java.lang.Object class and as Object class is super class of all other classes, so it is available to all classes.

java.util.Date class has overridden toString() method, that's why.

Read more

答案 2 :(得分:0)

This is because the Date class overrides the method toString() which is declated in java.lang.Object, allowing the Date to return a more readable representation.

In java.lang.Object the toString() is declared as:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Which is what DateFormat is using

相关问题