Both inheritance and composition are used to create relationships between classes.
The main difference is:
Inheritance = "is-a" relationship
Composition = "has-a" relationship
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();
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
class Car extends Vehicle {
}
Here:
Car is a Vehicle
Dog is an Animal
Car is a Vehicle
Manager is an Employee
Use inheritance when there is a genuine is-a relationship.