2

I'm trying to print out the details of a Person which contains an int and two Strings in my main method. I know I ave to use the toString() method but I can't remember how I would use this method to print out the details of each Person correctly. I'm assuming I must create a toString() method in my Person class and but I'm unsure as to what I must put into this. In my main method, I have put this:

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

What would go inside of here to complete this?

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

At the moment I'm getting this output:

Person: coursework.Person$1@15db9742
Person: coursework.Person$2@6d06d69c
Person: coursework.Person$3@7852e922
Person: coursework.Person$4@4e25154f

Any help is appreciated, thanks.

Ben
  • 153
  • 1
  • 9
  • After looking at that question I agree I think it i a duplicate, sorry for not finding it before posting. I'd delete this if I could but I can't as it already has answers. – Ben Dec 04 '16 at 07:54

2 Answers2

3

You should override Object#toString. Its signature:

public String toString()

Note that it returns a String, so you should be doing something like:

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

Of course you can improve this as you wish, I just wrote it for demonstration.


It's worth mentioning the meaning of the output you're getting now. As stated in the docs:

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

Maroun
  • 94,125
  • 30
  • 188
  • 241
1

toString method comes from parent class called java.lang.Object and its signature is public String toString(), so your toString should be:

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

The @Override annotation is used to override a superclass's method.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
SMA
  • 36,381
  • 8
  • 49
  • 73