Aggregation in Java — Java Technical Interview Questions & Answers
Aggregation in Java
Aggregation in Java
- Aggregation is HAS-A: one object uses another. Student has an Address. Model it with a field: Address address; inside Student. Not extends.
- Address can still exist if Student goes away — weaker ownership. Inheritance is IS-A. Aggregation is HAS-A. Composition is a stronger “part-of” idea (engine inside car).
- Using extends when the real relationship is HAS-A is the usual design mistake. Interview line: Student HAS-A Address — field reference, not extends.
- Let's take this on the board with one tiny Main class — no extra files. Aggregation in Java — output: Asha - Pune. Address can exist without Student — that is aggregation (HAS-A), not IS-A. Start from main, go line by line, and stop at each print. That output is the proof for Aggregation.
Technical Interview Tip: Say HAS-A with Student/Address. Contrast with extends.
Code Examples for Aggregation in Java
Example
class Address {
String city;
Address(String city) { this.city = city; }
}
class Student {
String name;
Address address; // HAS-A
Student(String name, Address address) {
this.name = name;
this.address = address;
}
}
public class Main {
public static void main(String[] args) {
Address a = new Address("Pune");
Student s = new Student("Asha", a);
System.out.println(s.name + " - " + s.address.city);
}
}Aggregation in Java — output: Asha - Pune. Address can exist without Student — that is aggregation (HAS-A), not IS-A.
How to Explain Aggregation in Java to an Interviewer
What is aggregation?
HAS-A Object uses another object as a field
Student and Address — extends or field?
Field Student HAS-A Address
IS-A vs HAS-A?
IS-A = inheritance HAS-A = aggregation