Explain the IS-A (inheritance) and Has-A (composition) relationships in Java.

IS-A and Has-A are two important relationships in Object-Oriented Programming that help model real-world relationships between classes. IS-A is achieved through inheritance, while Has-A is achieved through composition or aggregation.

Key Points: • IS-A represents inheritance, where one class is a specialized form of another class. • Has-A represents composition or aggregation, where one class contains an object of another class. • IS-A creates a parent-child relationship using the extends keyword. • Has-A creates a relationship by declaring objects as member variables. • Composition (Has-A) is generally preferred over inheritance because it provides greater flexibility and loose coupling.

IS-A Relationship (Inheritance):

An IS-A relationship exists when a subclass is a type of its superclass.

Example: A Dog IS-A Animal.

Code Example:

class Animal {

    void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {

    void bark() {
        System.out.println("Dog is barking");
    }
}

Here, Dog inherits the properties and behaviors of Animal because a Dog is an Animal.

Has-A Relationship (Composition):

A Has-A relationship exists when one class contains an object of another class.

Example: A Car HAS-A Engine.

Code Example:

class Engine {

    void start() {
        System.out.println("Engine Started");
    }
}

class Car {

    private Engine engine = new Engine();

    void startCar() {
        engine.start();
    }
}

Here, Car uses an Engine object because a Car has an Engine.

Comparison:

IS-A Relationship: • Implemented using inheritance • Represents specialization • Uses extends keyword • Creates tight coupling

Has-A Relationship: • Implemented using composition or aggregation • Represents containment • Uses object references • Creates loose coupling

Real-World Examples:

IS-A: • Dog IS-A Animal • Car IS-A Vehicle • Manager IS-A Employee

Has-A: • Car HAS-A Engine • House HAS-A Room • Department HAS-A Employee

Interview Tip: A concise interview answer is:

"IS-A represents inheritance, where a subclass is a specialized form of a superclass, such as Dog IS-A Animal. Has-A represents composition, where one class contains another class as a member, such as Car HAS-A Engine. In modern application design, Has-A relationships are generally preferred because they provide better flexibility and loose coupling."