将 Person 类型的对象转换为 String()?

converting object of type Person toString()?

我正在尝试打印出 Person 的详细信息,它在我的主要方法中包含一个 int 和两个字符串。我知道我必须使用 toString() 方法,但我不记得如何使用此方法正确打印出每个人的详细信息。我假设我必须在我的 Person class 中创建一个 toString() 方法,但我不确定我必须在其中放入什么。在我的主要方法中,我把这个:

System.out.println("Person: " + Person.Ben.toString());
System.out.println("Person: " + Person.Georgia.toString());
System.out.println("Person: " + Person.Tom.toString());
System.out.println("Person: " + Person.Beth.toString());

这里需要什么来完成这个?

public Person toString()
{
    //what goes here?
}

目前我得到这个输出:

Person: coursework.Person@15db9742
Person: coursework.Person@6d06d69c
Person: coursework.Person@7852e922
Person: coursework.Person@4e25154f

感谢任何帮助,谢谢。

toString 方法来自名为 java.lang.Object 的父 class 并且它的签名是 public String toString(),所以你的 toString 应该是:

@Override
public String toString() {
    StringBuilder sb = ...
    sb.append("Name: ");
    sb.append(name);
    sb.append("Age: ");
    sb.append(age);
    return sb.toString();
}

@Override 注释用于覆盖超级class 的方法。

您应该覆盖 Object#toString。它的签名:

public String toString()

请注意,它 returns 是 String,因此您应该这样做:

@Override
public String toString()
{
    return this.name + " " + this.age;
}

当然你可以随意改进,我只是为了演示而写的


值得一提的是您现在得到的输出的含义。如文档中所述:

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