I’m practicing learning how to write classes and creating “is” relationships between objects. In the code below, the first class “Person” defines a Person, and then in the second class “MarryDemo”, I see whether someone is married, who that spouse is, their address, etc. They even get divorced very shortly thereafter. The code is based on the examples of Jan Skansholm Java from the Beginning.
The problem is that I expected the result of the main method in MarryDemo to be “Kris Humphries”, “43 New Jersey Jets Street”, “null”, but instead of the spouse name I got Person@558ee9d6, with the spouse’s address and the spouse after divorce remaining as I expected them to be.
What does Person@558ee9d6 signify? Is that the location of the object that is referenced by the name “Kris Humphries”? Why does Person@558ee9d6 appear instead of the name?
//defines a person
public class Person {
//instance variables
private String name, address;
private Person spouse;
//constructor
public Person(string n) {
name = n;
}
//instance methods
public String getName() {
return name;
}
public void marry(Person p) {
spouse = p;
p.spouse = this;
}
public Person isMarriedTo() {
return spouse;
}
... //more methods for returning address, divorcing, etc.
}
//
public class MarryDemo {
public static void main (String[] arg) {
String name1 = "Kim Kardashian";
String name2 = "Kris Humphries";
Person p1 = new Person(name1);
Person p2 = new Person(name2);
p1.marry(p2);
System.out.println(p1.marriedTo());
p2.setAddress("43 New Jersey Jets Drive");
System.out.println(p1.marriedTo().getAddress());
p1.divorce();
System.out.println(p1.marriedTo());
}
}
You need to implement a
toString()method (as the default is not suitable). Most IDE will generate one for you.The class name and identity of the object. See Object.toString() for the code.
Nothing to do with the name. It is Person.toString() you are calling.
Where do you say you want the name to be printed instead?
If I replace
stringwithStringand use the IDE to generate a toString, the default isThis is obviously not suitable as this will go around forever. You can change it to