toString for Complex Objects: Nested References
You'll learn how to safely implement toString for objects that contain other objects, and how to avoid infinite loops when objects reference each other.
The Challenge of Nested Objects
When an object contains references to other objects, your toString implementation needs to handle them carefully. Simply calling toString on nested objects works fine—until you encounter circular references.
Think of it like describing your family tree: "I'm Alice, daughter of Bob" works fine. But if Bob's description says "Bob, father of Alice" and Alice's says "Alice, daughter of Bob who is the father of Alice who is the daughter of Bob..." you're stuck in an infinite loop!
Handling Nested Objects
For simple nesting, just call toString on contained objects:
class Address {
private String city;
private String state;
@Override
public String toString() {
return city + ", " + state;
}
}
class Person {
private String name;
private Address address;
@Override
public String toString() {
return "Person{name='" + name + "', address=" + address + "}";
}
}
The Circular Reference Problem
When objects reference each other (parent↔child, node↔node), naive toString causes StackOverflowError:
class Employee {
private String name;
private Employee manager; // Could reference back!
@Override
public String toString() {
// DANGER: if manager's manager is this employee...
return "Employee{name='" + name + "', manager=" + manager + "}";
}
}
Solution: Use identity (@hashCode) for circular-prone references or limit depth:
return "Employee{name='" + name + "', manager=" +
(manager == null ? "null" : manager.name) + "}";
Key Takeaway: When implementing toString for complex objects, call toString on nested objects freely, but protect against circular references by using identifying information (like name or ID) instead of full toString calls for potentially circular relationships.