Course Content
Core Java
About Lesson

Relationships between classes can be broadly categorized into two types: IS-A and HAS-A. The HAS-A relationship, also known as composition or aggregation, represents a scenario where one class contains references to objects of another class.

Has-A Relationship

Also known as composition/aggregation. It means that an instance of one class has a reference to an instance of another class or another instance of the same class. There is no such keyword that implements a Has-A relationship.

class Address {
    String city;
    String state;
    String country;

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

    void display() {
        System.out.println("City: " + city + ", State: " + state + ", Country: " + country);
    }
}

class Person {
    String name;
    int age;
    Address address; // Aggregation: Person has an Address

    Person(String name, int age, Address address) {
        this.name = name;
        this.age = age;
        this.address = address; // Aggregation relationship
    }

    void display() {
        System.out.println("Name: " + name + ", Age: " + age);
        address.display();
    }
}

public class Main {
    public static void main(String[] args) {
        Address address = new Address("New York", "NY", "USA");
        Person person = new Person("John Doe", 30, address);
        person.display();
    }
}

Is-A Relationship

The is-a relationship, also known as the inheritance relationship, represents a type of relationship between two classes where one class is a specialized version of another. It is based on inheritance. It implies that a subclass is a specific type of its superclass. For example, consider a class hierarchy with a superclass called “Animal” and a subclass called “Dog.” We can say that a Dog is an Animal, which reflects the is-a relationship.

To establish an is-a relationship between classes in Java, the keyword extends is used. The subclass extends the superclass, indicating that it inherits all the members (fields and methods) of the superclass.

class SubclassName extends SuperclassName {  
    // Subclass members  
}

Scroll to Top