我们为什么不能打印在java中直接对象? [英] Why we can't print object directly in java?
问题描述
我们可以打印一个数组容易使用的System.out.println
(虽然阵列也是一种在Java对象),但为什么我们不能直接打印对象不覆盖的toString()
方法?
例如:
int数组[] =新INT(2);
数组[0] = 10;
的System.out.println(数组[0]); //有用
obj对象=新的对象();
的System.out.println(OBJ); //它显示的类名和一些价值我不知道
它显示了类名和一些价值,我不知道。
块引用>嗯,这是一个
对象
实例的打印方式,并为对象
类的实例(即未分对象的类
)不能覆盖的toString
。有关
对象
,你必须自己决定,你多么希望字符串重新对象的presentation看起来像(通过重写<您的自定义子类code>的toString )。 Java没有决定给你。We can print an array easily using
System.out.println
(though array is also a kind of object in java) but why we can't print an object directly without overridetoString()
method?For example:
int array[]=new int(2); array[0]=10; System.out.println(array[0]); //it works Object obj=new Object(); System.out.println(obj); //it shows the classname and some value i don't know
解决方案"it shows the classname and some value i don't know"
Well, that's how an
Object
instance is printed, and for instances ofObject
class (i.e. not sub-classes ofObject
) you can't overridetoString
.For your custom sub-classes of
Object
, you must decide yourself how you wish the String representation of the object to look like (by overridingtoString
). Java doesn't decide it for you.这篇关于我们为什么不能打印在java中直接对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!