Java 对象的 toString() 方法 -Java 学习笔记 (16)

 Java中所有对象都自Object类继承了toString()方法。
toString()方法返回当前对象的字符串表示
在用到对象的字符串表示时,系统会自动调用对象的toString()方法,如print()函数,字符串"+"运算等。

自定义类的toString()表示

public   class  ToStringTest  {
    
public static void main (String[] args) {
        Person p1 
= new Person("zhaohongliang");
        System.out.println(p1);
    }

}

class  Person  {
    
private String name;
    
public Person(String name) {
        
this.name=name;
    }

}
运行System.out.println(p1);时
系统调用的是p1的toString()方法
运行结果:
Person@1fc4bec
这个结果看起来怪怪的,这是因为在默认情况下(不重载),toString()的结果格式为
类名@对象的16进制Hash表示
Object类toString()方法的API Docs

toString

public String toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())
 

 

Returns:
a string representation of the object.

所以,如果可能用到的话,应当重写这个方法

public   class  ToStringTest  {
    
public static void main (String[] args) {
        Person p1 
= new Person("zhaohongliang");
        System.out.println(p1);
    }

}

class  Person  {
    
private String name;
    
public Person(String name) {
        
this.name=name;
    }

    
public String toString() {
        
return "My name is "+this.name+".";
    }

}
运行结果
My name is zhaohongliang.
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值