Super Keyword in Java
🔹 super Keyword in Java
The super keyword is used in a subclass to refer to members (variables or methods) of its immediate superclass.
✅ Uses of super:
-
Access superclass constructor
-
Access superclass methods
-
Access superclass variables
1. Using super() to Call Superclass Constructor
By default, when a subclass constructor is called, it implicitly calls the no-argument constructor of the superclass using super().
Output:
2. Using super to Access Superclass Method
3. Using super to Access Superclass Variable
🔹 Order of Constructor Calls in Inheritance
In Java, when a subclass object is created:
-
Superclass constructor is called first
-
Then the subclass constructor is called
This ensures that the parent part of the object is initialized before the child part.
📌 Example:
Output:
✅ Even though we only created an object of class C, constructors of B and A are called first, in that order.
📌 Summary
| Concept | Description |
|---|---|
super() | Calls the immediate superclass constructor. Must be the first statement in subclass constructor. |
super.method() | Calls a method from the superclass. |
super.variable | Accesses a variable from the superclass (if hidden by subclass variable). |
| Constructor Call Order | Parent constructor → Child constructor |
Comments
Post a Comment