1. What is Inheritance?
Inheritance is a mechanism in Java by which one class (child/subclass) can acquire the properties (fields) and behaviors (methods) of another class (parent/superclass). It promotes code reusability and method overriding.
2. Types of Inheritance in Java
Java supports several types of inheritance:
Single Inheritance A class inherits from one parent class.
Multilevel Inheritance
A class inherits from a subclass, forming a chain of inheritance.
Hierarchical Inheritance
Multiple classes inherit from the same parent class.
Note: Java does not support multiple inheritance (a class cannot inherit from more than one class) to avoid ambiguity. But multiple inheritance can be achieved using interfaces.
3. super
Keyword
- Used to access parent class members (fields/methods/constructors).
class Animal {
void eat() { System.out.println("Animal eats"); }
}
class Dog extends Animal {
void eat() {
super.eat(); // call parent method
System.out.println("Dog eats");
}
}
4. Benefits of Inheritance
- Code reusability: Use existing code instead of rewriting it.
- Method overriding: Customize inherited methods.
- Polymorphism: Objects can take multiple forms using inherited types.
5. Summary Table
Concept | Description |
---|---|
extends | Keyword used for inheritance |
Parent/Superclass | Class whose properties are inherited |
Child/Subclass | Class that inherits from another class |
super | Access parent class methods, fields, constructors |
Multiple Inheritance | Not supported with classes, only via interfaces |
If you want, I can also draw a diagram showing all types of inheritance in Java to make it visually clear.
Do you want me to do that?