为什么system.out.println(新员工)的输出是system.out.println(新日期)的地址和输出是今天的日期? [英] Why output of system.out.println(new employee) is address and output of system.out.println(new date) is todays date ?

查看:71
本文介绍了为什么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.


这篇关于为什么system.out.println(新员工)的输出是system.out.println(新日期)的地址和输出是今天的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆