It allows a class (called a subclass or child class) to inherit fields and methods from another class (called a superclass or parent class).
🔹 Why Use Inheritance?
- Reusability: Reuse code from existing classes.
- Extensibility: Extend or add new features to existing classes.
- Maintainability: Easier to manage code.
- Polymorphism: Allows a subclass to be treated as an instance of its superclass. 🔸 Basic Syntax
class Parent {
void display() {
System.out.println("This is the parent class");
}
}
class Child extends Parent {
void show() {
System.out.println("This is the child class");
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
obj.display(); // Inherited method
obj.show(); // Child's own method
}
}
🔹 Types of Inheritance in Java
Single Inheritance
-One class inherits from another.
Multilevel Inheritance
A class inherits from a derived class.
Hierarchical Inheritance
Multiple classes inherit from a single parent class.
❌ Multiple Inheritance (via classes) is not supported in Java (to avoid ambiguity issues like the Diamond Problem).
✅ But Java supports multiple inheritance using interfaces.
🔸 super Keyword
Used to:
Access superclass methods or constructors.
class Parent {
void greet() {
System.out.println("Hello from parent");
}
}
class Child extends Parent {
void greet() {
super.greet(); // Call parent version
System.out.println("Hello from child");
}
}
🔸 Access Modifiers in Inheritance
- private: Not accessible in child class.
- protected: Accessible in child class, even if it's in a different package.
- public: Always accessible.
- default (no modifier): Accessible in the same package only.
🔹 Why We Use super() in Java:
- To call the parent class constructor:
- When a subclass is created, it often needs to initialize things from its parent class. super() lets you do that.
- It must be the first statement in the subclass constructor.
- To reuse parent class initialization code, instead of rewriting it in the child class.
🔸 When you don't write super() explicitly:
Java automatically inserts a default super() call if there’s no constructor with parameters in the parent class.
🔹 Other Forms of super (not super()) **(tbd)**
Besides super() (constructor call), Java also allows:
- super.someMethod() → Call a method from the parent class.
- super.someVariable → Access a variable from the parent class.