欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

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

来源: javaer 分享于  点击 17731 次 点评:129

Java基础篇----toString()方法,基础篇----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".
    }
}


相关文章

    暂无相关文章

用户点评