Inheritance and Polymorphism
Let's dive deep into Inheritance and Polymorphism, two fundamental pillars of Object-Oriented Programming (OOP) in Java.
🔷 INHERITANCE in Java
📌 Definition:
Inheritance is the mechanism in Java by which one class acquires the properties and behaviors (fields and methods) of another class.
-
The class that inherits is called the subclass (or child class).
-
The class from which it inherits is the superclass (or parent class).
✅ Syntax:
Example:
✅ Output:
🔑 Types of Inheritance in Java:
Type | Supported in Java? | Example |
---|---|---|
Single Inheritance | ✅ Yes | class B extends A |
Multilevel | ✅ Yes | A → B → C |
Hierarchical | ✅ Yes | A → B, A → C |
Multiple Inheritance | ❌ (via classes) ✅ via interfaces | class C implements A, B |
🔷 POLYMORPHISM in Java
📌 Definition:
Polymorphism means “many forms”. In Java, it allows objects to behave differently based on the context, even if they share the same interface or method name.
There are two types:
🔸 1. Compile-time Polymorphism (Method Overloading)
-
Same method name with different parameters (type or number).
-
Resolved at compile time.
✅ Example:
🔸 2. Runtime Polymorphism (Method Overriding)
-
Same method name and signature in both superclass and subclass.
-
Resolved at runtime using dynamic method dispatch.
✅ Example:
Differences Between Inheritance and Polymorphism
Feature | Inheritance | Polymorphism |
---|---|---|
Meaning | Reuse code from parent class | Same method behaves differently |
Type | Is-a relationship | Many forms |
Use | Code reuse | Flexibility and dynamic behavior |
Achieved by | extends keyword | Overloading & Overriding |
Real-World Analogy
Concept | Example |
---|---|
Inheritance | A car is a type of vehicle — it inherits basic features like wheels, engine. |
Polymorphism | A remote control works for TV, AC, or fan — the button is the same, but the result differs. |
✅ Summary
🔹 Inheritance:
-
Enables code reuse.
-
Subclass inherits fields and methods from the superclass.
🔹 Polymorphism:
-
Enables flexibility.
-
Same method name can behave differently (overloading/overriding).
Comments
Post a Comment