What is Inheritance:
Inheritance is a mechanism where one class (called a child or subclass) acquires the properties and behaviors of another class (called a parent or superclass). This allows us to reuse code and create relationships between classes.
Why do we need Inheritance:
- Code Reusability: Instead of writing the same code over and over, you can write it once in a parent class and reuse it in multiple child classes.
- Organization: Inheritance helps organize your code in a logical, hierarchical way that mirrors real-world relationships.
- Easier Maintenance: When you need to make changes, you only update the parent class, and all child classes automatically inherit those changes.
- Extensibility: You can easily add new features to existing code without modifying it.
Types of Inheritance:
1. Single Inheritance
One child class inherits from one parent class
class Parent {
void show() {
System.out.println("This is parent class");
}
}
class Child extends Parent {
void display() {
System.out.println("This is child class");
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
obj.show(); // Inherited method
obj.display(); // Child method
}
}
2. Multiple Inheritance
Java does NOT support multiple inheritance with classes. Because, If both parent classes have the same method, compiler will not know which method need to be called. So, Java uses interfaces instead to achieve similar functionality.
Top comments (0)