Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟣 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

TypeAlso calledHow
Compile-timeMethod OverloadingSame method name, different parameters — resolved by the compiler.
RuntimeMethod OverridingChild 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.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 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.
Next topicAbstraction and Interfaces Your progress: 20 / 61 (33%) · Lesson 21 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free