Java基础篇----toString()方法

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.

toString()方法就是把对象转换成String类型的表示形式,转换的算法根据类型和实际需要而定。
比如一个Integer对象的toString方法就是把这个对象表示的整数转化成字符串,133就成了"133"。
也有根据实际需要来定toString方法的,比如一个Person类:
class Person {
   String firstName;
   String familyName;
   ...
}
你可以写一个toString方法,它可以把Person的对象转换成familyName字符串,或者转换成firstName + familyName的字符串。
比如Person类
public class Person {
    private String name = null;
    private int age = 0;
    public Person(String name, int age) {
         this.name = name;
         this.age  = age;
    }
    public String toString() {
         return name;
    }
}
--------------
public class Test {
    public static void main(String[] args) {
         Person p = new Person("Jack", 20);
         System.out.println(p);// 这时会输出"Jack".
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值