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)
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.