Objects inside objects
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A field can hold an object, not just a number or text. A Student can have an Address field, and the address has its own city and PIN code. This is HAS-A in code: a bigger object built from smaller ones.
A field whose type is a class
A class-type field (also called an object field) is a field whose type is a class, such as private Address address;. It lets one object hold another object as its part.
A student, a teacher and a shop each have a city and a PIN code. Write those once in an Address class, then give Student a field of type Address.
Example 1 · A student with an address
class Address { private String city; private int pin;
Address(String city, int pin) { this.city = city; this.pin = pin; }
String getCity() { return city; } int getPin() { return pin; }}
class Student { private String name; private Address address;
Student(String name, Address address) { this.name = name; this.address = address; }
String getName() { return name; } Address getAddress() { return address; }}
public class AddressDemo { public static void main(String[] args) { Address home = new Address("Pune", 411001); Student s = new Student("Aarav", home); System.out.println(s.getName() + " lives in " + s.getAddress().getCity()); System.out.println("PIN: " + s.getAddress().getPin()); }}Aarav lives in Pune PIN: 411001
What this code does
private Address address;is a class-type field. The constructor receives a readyAddressobject and stores it.s.getAddress().getCity()first gets the address object, then asks it for the city.
Example 2 · Building a ticket from parts
class Passenger { private String name; private int age;
Passenger(String name, int age) { this.name = name; this.age = age; }
String describe() { return name + " (" + age + ")"; }}
class Train { private int number; private String name;
Train(int number, String name) { this.number = number; this.name = name; }
String describe() { return number + " " + name; }}
class Ticket { private Passenger passenger; private Train train; private int fare;
Ticket(Passenger passenger, Train train, int fare) { this.passenger = passenger; this.train = train; this.fare = fare; }
void print() { System.out.println("Passenger: " + passenger.describe()); System.out.println("Train: " + train.describe()); System.out.println("Fare: Rs. " + fare); }}
public class TicketDemo { public static void main(String[] args) { Passenger p = new Passenger("Kavya", 20); Train t = new Train(12627, "Karnataka Express"); Ticket ticket = new Ticket(p, t, 845); ticket.print(); }}Passenger: Kavya (20) Train: 12627 Karnataka Express Fare: Rs. 845
What this code does
- The parts (
Passenger,Train) are built first, then passed into theTicketconstructor. The ticket is the whole. print()asks each part to describe itself. The ticket does not need to know the passenger's or train's fields.
Why not put city and pin straight into Student? They belong together, and other classes need them too. One Address class keeps that code, and any check such as a six-digit PIN, in one place.
A whole can have several parts. Example 2 builds a train ticket from a passenger and a train: the parts are made first, then passed in.
The field holds a reference
A shared part is one object that two or more wholes hold references to. Because there is only one object, a change made through one whole is seen through every other whole.
The address field does not hold the address itself. It holds a reference to a separate object, just like Student b = a; in Many objects, references and null (opens in a new tab). So two students can point at one Address.
Example 3 · Two students, one address object
class Address { private String city;
Address(String city) { this.city = city; }
String getCity() { return city; } void setCity(String city) { this.city = city; }}
class Student { private String name; private Address address;
Student(String name, Address address) { this.name = name; this.address = address; }
void show() { System.out.println(name + ": " + address.getCity()); }}
public class SharedDemo { public static void main(String[] args) { Address home = new Address("Pune"); Student rohan = new Student("Rohan", home); Student diya = new Student("Diya", home); home.setCity("Mumbai"); rohan.show(); diya.show(); }}Rohan: Mumbai Diya: Mumbai
What this code does
- Both students store a reference to the same
Addressobject; no copy was made. That is right for siblings sharing a home. - Changing the city through
homechanges what both students see, because there is only one address object, as the picture above shows.
Sharing is right when the part really is one thing, like the home two siblings live in. When each whole needs its own part, give each one its own new Address(...). Aggregation (opens in a new tab) builds on this idea of shared parts.
Predict the output
One Address or two?
Read the code and pick what it prints.
Round 1 of 2
Rohan and Diya are given the same Address object. The city is changed through Rohan.
Reaching a part: chained calls
Method chaining is calling a method on the object that another call returned, in one expression, as in s.getAddress().getCity(). Each dot works on the result of the call before it.
To print a student's city, ask the student for its address, then ask the address for its city. Both steps fit in one expression.
Student s = new Student("Aarav", new Address("Pune", 411001));
Address home = s.getAddress(); // step 1: ask the studentString city = home.getCity(); // step 2: ask the address
String same = s.getAddress().getCity(); // both steps in one chainSystem.out.println(city + " " + same);Read a chain left to right: s.getAddress() returns an Address object, and .getCity() runs on that object. The last line prints Pune Pune.
Short chains are fine. A long one like order.getCustomer().getAddress().getCity() is fragile: every dot is one more object that could be missing, and the caller must know three classes. Give the outer class a method such as deliveryCity() that does the reaching for you.
A missing part: NullPointerException
An optional part is a part a whole may not have yet, such as a patient's doctor. Its field stays null until it is set, so the whole must check for null before using it.
If the constructor never sets address, the field stays null. Creating the student works; the crash comes later, when a method is called on the missing part, as in Many objects, references and null (opens in a new tab).
Example 4 · A missing part crashes the program
class Address { private String city;
Address(String city) { this.city = city; }
String getCity() { return city; }}
class Student { private String name; private Address address;
Student(String name) { this.name = name; }
Address getAddress() { return address; }}
public class NullPartDemo { public static void main(String[] args) { Student s = new Student("Arjun"); System.out.println("Student created"); System.out.println(s.getAddress().getCity()); }}Student created Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Address.getCity()" because the return value of "Student.getAddress()" is null at NullPartDemo.main(NullPartDemo.java:26)
What this code does
- This constructor never sets
address, so it staysnull. Creating the student works fine. - The crash comes only when
.getCity()is called on thenullreturned bygetAddress(). The message names both methods.
Example 5 · The fix: ask the whole, check for null
class Address { private String city;
Address(String city) { this.city = city; }
String getCity() { return city; }}
class Student { private String name; private Address address;
Student(String name) { this.name = name; }
Student(String name, Address address) { this.name = name; this.address = address; }
String getCity() { if (address == null) { return "Not given"; } return address.getCity(); }
void show() { System.out.println(name + ": " + getCity()); }}
public class SafePartDemo { public static void main(String[] args) { new Student("Arjun").show(); new Student("Priya", new Address("Kochi")).show(); }}Arjun: Not given Priya: Kochi
What this code does
- The student now has its own
getCity(). Callers ask the student, not the address, so the null check lives in one place. - When the address is optional, check
address == nullbefore using it. Arjun has no address, so a safe default is printed.
There are two fixes. If every student must have an address, take it in the constructor. If the part is truly optional, the whole checks for null in one method, and every caller uses that method.
A common cause of a null part is address = address; in the constructor, which sets the parameter, not the field. Write this.address = address;, as in The this keyword (opens in a new tab).
Next step
Check your understanding
11 quick questions