Java Polymorphism π¶
Mentor's Note: "Poly" means Many, and "Morph" means Forms. Polymorphism is the ability of an object to take many forms. It allows you to perform a single action in different ways! π‘
π The Scenario: The Superhero π¦Έ¶
Imagine a person named Bruce Wayne.
- The Logic: To some people, he is a Billionaire π°. To others, he is Batman π¦.
- The Action: If you tell Bruce to "Go to Work," he either goes to a board meeting or fights crime.
- The Result: The command is the same ("Go to Work"), but the behavior changes depending on which "form" he is currently using. β
π Concept Explanation¶
1. What is Polymorphism?¶
Polymorphism occurs when we have many classes that are related to each other by inheritance.
2. Static vs. Dynamic¶
- Static (Compile-time): Achieved through Method Overloading (same name, different parameters). π¦
- Dynamic (Runtime): Achieved through Method Overriding (child class changes the parent's method). π¦
π¨ Visual Logic: One Command, Many Results¶
graph TD
A[Command: makeNoise()] --> B[Animal Class]
B -- "If Dog πΆ" --> C[Bark!]
B -- "If Cat π±" --> D[Meow!]
B -- "If Bird π¦" --> E[Tweet!]
π» Implementation: The Animal Lab¶
// π Scenario: Different Animals speaking
// π Action: Overriding the parent method
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound π");
}
}
class Pig extends Animal {
public void makeSound() {
System.out.println("The pig says: wee wee π·");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("The dog says: bow wow πΆ");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Generic
Animal myPig = new Pig(); // Polmorphic
Animal myDog = new Dog(); // Polymorphic
myAnimal.makeSound();
myPig.makeSound(); // ποΈ Outcome: "The pig says: wee wee"
myDog.makeSound(); // ποΈ Outcome: "The dog says: bow wow"
}
}
π Sample Dry Run¶
| Reference Type | Object Type | Command | Final Output |
|---|---|---|---|
Animal |
Dog |
.makeSound() |
"bow wow" πΆ |
Animal |
Pig |
.makeSound() |
"wee wee" π· |
π Technical Analysis¶
- Why use it?: It makes your code extremely flexible. You can write a method that accepts an
Animalparameter, and it will automatically work for Dogs, Cats, and Pigs without you changing a single line! π§
π― Practice Lab π§ͺ¶
Task: The Shape Drawer
Task: Create a parent class Shape with a method draw(). Create child classes Circle and Square. Override the draw() method to print "Drawing Circle" and "Drawing Square".
Hint: Use Animal example as a template! π‘
π‘ Interview Tip π¶
"Interviewers love asking: 'Can you override a static method?' Answer: No. Static methods belong to the class, not the object instance, so they don't support polymorphism."
π‘ Pro Tip: "One interface, multiple implementationsβthat's the power of being flexible!" - Anonymous
β Back: Aggregation (Weak Has-A) | Next: Abstraction & Interface β