Inheritance allows one class to acquire the fields and methods of another class.
It promotes code reuse and allows us to create a relationship between classes.
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}
Here:
Animal → Parent / SuperclassDog → Child / Subclassextends → Creates the inheritance relationshipDog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Dog's own method
extendsextends is used when a class inherits from another class.
class Dog extends Animal {
}
This means:
Dogis anAnimal.
Java supports single class inheritance:
Animal
↓
Dog
supersuper refers to the immediate parent class.
It is commonly used to access the parent's fields, methods, or constructor.