Java Inheritance
🔹 Java Inheritance
Inheritance in Java is an OOP concept where a class (child/subclass) acquires the properties and methods of another class (parent/superclass).
It promotes code reusability and establishes a hierarchical relationship between classes.
✅ 1. Types of Inheritance in Java
| Type | Description |
|---|---|
| Single Inheritance | One child inherits from one parent |
| Multilevel Inheritance | Class inherits from another class, which inherits from another class |
| Hierarchical Inheritance | Multiple child classes inherit from one parent class |
| Multiple Inheritance (via Interfaces) | Java does not support multiple class inheritance directly but supports it using interfaces |
✅ 2. Syntax
-
extendskeyword is used for inheritance. -
Child class inherits all accessible members of parent class.
✅ 3. Example 1: Single Inheritance
📌 Output:
✅ 4. Example 2: Multilevel Inheritance
📌 Output:
✅ 5. Example 3: Hierarchical Inheritance
📌 Output:
✅ 6. Key Points About Inheritance
-
Use
extendskeyword to inherit from a class. -
Private members of parent class are not inherited.
-
Promotes code reusability and hierarchy.
-
Constructors are not inherited, but child can call parent constructor using
super. -
Java does not support multiple class inheritance to avoid ambiguity (use interfaces instead).
