打印 对象 java,我们为什么不能打印在java中直接对象?

本文解释了为什么在Java中不能直接打印非`toString()`方法覆盖的对象,指出Object类实例的默认行为,并强调自定义子类时需重写toString方法以定义对象的字符串表示形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值