【OOP】Kind of Relations in OOP

Posted by 西维蜀黍 on 2018-11-12, Last Modified on 2024-05-02
  1. Is A (Inheritence)
  2. Has A (Composition)
  3. Works With (Collaboration)

Is A (Inheritence)

In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance.

It is just like saying “A is a B type of thing”. For example, Apple is a Fruit, Car is a Vehicle, etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House.

It is a key point to note that you can easily identify an IS-A relationship. Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to have IS-A relationship.

Has A (Composition)

Composition (HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom.

package relationships;

class Car {
    // Methods implementation and class/Instance members
    private String color;
    private int maxSpeed;

    public void carInfo() {
        System.out.println("Car Color= " + color + " Max Speed= " + maxSpeed);
    }

    public void setColor(String color) {
        this.color = color;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
}

class Maruti extends Car {
    //Maruti extends Car and thus inherits all methods from Car (except final and static)
    //Maruti can also define all its specific functionality
    public void MarutiStartDemo() {
        Engine MarutiEngine = new Engine();
        MarutiEngine.start();
    }
}

As shown above, Car class has a couple of instance variable and few methods. Maruti is a specific type of Car which extends Car class means Maruti IS-A Car.

Maruti class uses Engine object’s start() method via composition. We can say that Maruti class HAS-A Engine.

Works With (Collaboration)

Reference