Inheritance and Polymorphism
Inheritance and Polymorphism
Inheritance (Hierarchy):
Constructor chaining:
Git link for code:
https://github.com/PuneetKumarSinghIT/java
Super Keyword usage:
If a person want to call specific constructor of his super class means parent which is inherited by that perticular class then that child class need to give super(parameter) to call the constructor of parent class.
Please follow git repo for detailed code:
https://github.com/PuneetKumarSinghIT/java
The super keyword in Java is a powerful tool used to refer to the immediate parent class. It is especially useful in class inheritance scenarios.
- Accessing Parent Class Methods ( Method Overriding Context):
super.methodName() is essential.- Accessing Parent Class Data Members(Variable Shadowing Context):
Why it's useful: Avoids ambiguity and allows access to hidden fields from the parent class, which is critical in debugging or layered logic.
- Constructor Chaining to Parent Class Constructor:
- In Complex Business Logic where base logic is shared and extended:
Why it's useful: Promotes code reuse, separation of concerns, and allows base logic to be used and extended in a predictable way.
- When Accessing Parent Class Methods from an Inner Class Inside the Child:
Why it's useful: Useful in advanced use cases involving inner classes where direct inheritance semantics are not available.
| Use Case | super Used For |
Key Benefit |
|---|---|---|
| Method overriding | Method call | Invoke parent logic within overridden method |
| Variable shadowing | Field access | Resolve field name conflicts |
| Constructor chaining | Constructor call | Ensure proper object initialization |
| Business logic reuse | Method call | Maintain DRY and layered logic |
| Access from inner class | Method call | Access base class behavior from inner scope |
Polymorphism:
Poly - means, Morphism - Forms.
In Java it means one object can have many forms. Best use of inheritance is because of polymorphism.
Types of Polymorphism:
- Runtime polymorphism (overriding)
- Compile time polymorphism (overloading)
Compile type polymorphism (overloading):
Conditions are:
- Method name should be same
- Return type of method must be same
- datatype of parameters should be different
Methods which are not allowed:
As compiler is not able to identify the called method. As both methods name is same and list of parameter and order is also same.
Runtime polymorphism (overriding):
You cannot catch it's error at the time of compiling.
Same situation at the time of run compiler is not able to understand which method to call.
So method of object is called not of datatype.

















Comments
Post a Comment