我们为什么不能打印在java中直接对象? [英] Why we can't print object directly in java?

查看:241
本文介绍了我们为什么不能打印在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 override toString() 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 of Object class (i.e. not sub-classes of Object) you can't override toString.

For your custom sub-classes of Object, you must decide yourself how you wish the String representation of the object to look like (by overriding toString). Java doesn't decide it for you.

这篇关于我们为什么不能打印在java中直接对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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