Both inheritance and composition are used to create relationships between classes.

The main difference is:

Inheritance = "is-a" relationship

Composition = "has-a" relationship


1. Inheritance — "Is-A"

Inheritance means one class inherits properties and methods from another class.

We use the extends keyword.

class Animal {

    void eat() {
        System.out.println("Eating");
    }
}

class Dog extends Animal {

    void bark() {
        System.out.println("Barking");
    }
}

Here:

Dog is an Animal

The Dog class automatically gets the eat() method from Animal.

Dog dog = new Dog();

dog.eat();
dog.bark();

Another Example

class Vehicle {

    void start() {
        System.out.println("Vehicle started");
    }
}

class Car extends Vehicle {

}

Here:

Car is a Vehicle

Common Examples

Dog is an Animal
Car is a Vehicle
Manager is an Employee

Use inheritance when there is a genuine is-a relationship.