Slide 1
Slide 2
Slide 3

Aggregation in java programming (V60)

No Comments

Aggregation
Aggregation is a relationship between two classes in which one class has an instance of another class.
For example, when object A has a reference to another object B, we can say that object A has a HAS-A relationship with object B, and this is called Aggregation in Java Programming.

Aggregation helps in code reusability. Object B may contain useful methods that can be used by multiple objects. Any class that has object B can use its methods.

Create Project Name: StudentInformation

  Source Code1: Address.java

Copied!
public class Address {
    String city, country;

    public Address(String city, String country) {
        this.city = city;
        this.country = country;
    }
}

Source Code2:  Student.java

Copied!
public class Student {
    int id;
    String name;
    Address address; // Aggregation

    public Student(int id, String name, Address address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    public void display() {
        System.out.println("ID: " + id + ", Name: " + name);
        System.out.println("City: " + address.city + ", Country: " + address.country);
    }
}

Source Code3: StudentInformation.java

Copied!
public class StudentInformation {

    public static void main(String[] args) {
        Address addr = new Address("Phnom Penh", "Cambodia");
        Student s = new Student(101, "Seanghon", addr);
        s.display();
    }
}

Result:


Watch the video:


back to top