Inheritance
What is Inheritance in Java
Inheritance is a mechanism where one class acquires properties and methods of another class. It helps in code reuse and reduces redundancy.
Types of Inheritance in Java
Single Inheritance
One class inherits from another.
class Animal {
void eat(){
System.out.println(“Eating”);
}
}
void eat(){
System.out.println(“Eating”);
}
}
class Dog extends Animal {
void bark(){
System.out.println(“Barking”);
}
}
Multilevel Inheritance
A class inherits from another class, which is also derived from another class.
Hierarchical Inheritance
Multiple classes inherit from a single parent class.
Benefits of Inheritance
- Code reusability
- Reduces duplication
- Improves maintainability
- Supports method overriding
