您的位置:首页 > 编程语言 > Java开发

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

2007-05-31 23:44 591 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐