Sobes.tech
Junior

What do the expressions "is" and "has" imply in the context of object-oriented programming (OOP) principles?

sobes.tech AI

Answer from AI

"Is-a" relates to inheritance. It is a relationship between classes where one class inherits properties and behavior from another. The subclass is a specialized version of the parent class. For example, Dog is an Animal.

"Has-a" relates to composition. It is a relationship between objects where one object includes another object as its part. One object "has" another object. For example, Car has an Engine.

Comparison:

Relationship OOP Principle Description Example
Is-a Inheritance Specialization, extension of a class Dog is-a Animal
Has-a Composition Part of a whole, aggregation of objects Car has-a Engine

Code example for "is-a" (inheritance):

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

// Child class
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking.");
    }
}

Code example for "has-a" (composition):

// Class representing a part
class Engine {
    void start() {
        System.out.println("Engine starting.");
    }
}

// Class that has a part
class Car {
    private Engine engine; // Engine object as part of Car

    public Car() {
        this.engine = new Engine(); // Initialize Engine when creating Car
    }

    void start() {
        engine.start(); // Delegate call to part's method
        System.out.println("Car started.");
    }
}

Inheritance establishes a strong "is-a" relationship, while composition establishes a weaker "has-a" relationship. It is preferable to use composition when possible to increase flexibility and reduce dependencies between classes.

What do the expressions "is" and "has" imply in the… - sobes.tech