🟣 OOP · Lesson 20
Polymorphism in Java
In this lesson: Method overloading vs overriding — compile-time and runtime polymorphism in Java with examples and output. In Hindi & English.
What is Polymorphism?
Polymorphism means "many forms". In Java it lets one method name behave differently depending on the object or the arguments. It is one of the four pillars of OOP and makes code flexible and extensible.
💡 Meaning
Poly = many, morph = forms. The same action (e.g. draw()) takes many forms for different shapes.
Two Types of Polymorphism
| Type | Also called | How |
|---|---|---|
| Compile-time | Method Overloading | Same method name, different parameters — resolved by the compiler. |
| Runtime | Method Overriding | Child class redefines a parent method — resolved at runtime. |
1) Overloading (compile-time)
Java
class Calc { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } // same name, different types }
▶ Output
add(2,3) → 5 add(2.5,1.5) → 4.0
2) Overriding (runtime)
Java
class Animal { void sound() { System.out.println("Some sound"); } } class Cat extends Animal { void sound() { System.out.println("Meow"); } // overrides parent } Animal a = new Cat(); a.sound(); // runtime picks Cat's version
▶ Output
Meow
Why It's Useful
- Write general code (e.g.
Animal a) that works for many specific types. - Add new subclasses without changing existing code.
- Cleaner APIs — one method name instead of many.
⚠️ Overloading vs Overriding
Overloading = same class, different parameters (compile-time). Overriding = parent & child, same signature (runtime). Don't confuse the two.
Summary
- Polymorphism = one name, many forms.
- Compile-time (overloading) and runtime (overriding).
- Makes code flexible, reusable and easy to extend.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
