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;
}
}
系统调用的是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
toStringmethod 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
toStringmethod for classObjectreturns 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.
本文介绍了Java中Object类的toString()方法,默认情况下该方法返回一个包含类名、'@'符号及对象十六进制哈希码的字符串。文章通过示例展示了如何重写toString()方法来提供更具意义的对象描述。

4624

被折叠的 条评论
为什么被折叠?



