为什么system.out.println(新员工)的输出是system.out.println(新日期)的地址和输出是今天的日期?

问题描述:

以下程序的输出是

o / p:

员工@ ------(某地址)

今天日期



为什么预定义类Date的对象在传递给println方法时的行为与用户定义类的对象不同?



我尝试过:



import java.util。*;

import java.time 。*;



班级员工(){

//空

}



class main {

public static void main(String [] args){

System.out.println(new Employee); //用户定义类的对象

System.out.println(new Date); //预定义日期类的对象

}

}

output of following program is
o/p:
Employee@------(some address)
todays date

why object of predefinined class Date behaves differently than object of user defined class when it is passed to println method?

What I have tried:

import java.util.*;
import java.time.*;

class Employee(){
// Empty
}

class main{
public static void main(String[] args){
System.out.println(new Employee); //object of user defined class
System.out.println(new Date); // object of predefined Date class
}
}

调用时print() println()传递一个对象,String.valueOf(Object) [ ^ ]

调用方法并打印返回的字符串(参见 PrintStream(Java Platform SE 7) [ ^ ])。因此输出取决于如何为对象实现 toString()方法( toString()最终被调用时该对象不为null)。



对于日期对象,请参阅 Date.toString()(Java Platform SE 7) [ ^ ]。



对于用户定义的对象,由您来实现该方法并定义要返回的内容。
When calling print() or println() passing an object, the String.valueOf(Object)[^]
method is called and the returned string is printed (see PrintStream (Java Platform SE 7 )[^] ). So the output depends on how the toString() method is implemented for the object (toString() is finally called when the object is not null).

For the Date object see Date.toString() (Java Platform SE 7 )[^].

For a user defined object it is up to you to implement the method and define what to be returned.