[Java]Object类的toString()方法

时间:2021-12-16 16:14:03

Object类是所有类的父类,Object中有一个方法为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()方法返回的是“ 类名 + '@' + 类的hashcode的十六进制”,因此,这样的表达方式很少有人能看懂,所用在用的时候就要重写此方法。


程序一:(没有重写toString)

class Person extends Object
{
String name = "lavender";
int age = 21;
}
public class toStringDemo1 {

public static void main(String[] args) {
Person p = new Person();
System.out.println(p);

}

}
程序运行结果为:

Person@327800e9


程序二:(将toString()方法重写)

class Person extends Object
{
String name = "lavender";
int age = 21;

//重写Object类中的toString()方法
public String toString()
{
return "I am " + this.name + ", I am " + age + " years old.";
}
}
public class toStringDemo1 {

public static void main(String[] args) {
Person p = new Person();
System.out.println(p);

}

}
运行结果:

I am lavender, I am 21 years old.