MCAWALA

Java Vertical Menu

🌀 Java Polymorphism क्या है? – आसान भाषा में

🔷 What is Polymorphism?

Polymorphism का मतलब है "कई रूप" (many forms)। Java में इसका मतलब है कि एक ही method या object अलग-अलग तरीके से behave कर सकता है।

यह Java की Object-Oriented Programming (OOP) की चार मुख्य विशेषताओं में से एक है:

  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction

📘 Real-Life Example:

एक method makeSound() है। Dog, Cat, और Cow इस method को अपने तरीके से define कर सकते हैं:

  • Dog बोलेगा: Bark
  • Cat बोलेगी: Meow
  • Cow बोलेगी: Moo

🧱 Types of Polymorphism in Java

Type नाम कैसे होता है?
Compile-time Method Overloading Same class में same method name, अलग parameters
Runtime Method Overriding Subclass में parent method को override करना

✅ Method Overloading (Compile-time Polymorphism)

Same method name, लेकिन अलग arguments।

class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }
}

✅ Method Overriding (Runtime Polymorphism)

Subclass में inherited method को फिर से define करना।

class Animal {
    void makeSound() {
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {
    void makeSound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog(); // Parent type, Child object
        a.makeSound();        // Output: Dog barks
    }
}

🎯 Polymorphism के फायदे:

  • ✅ Code reuse होता है
  • ✅ Program ज़्यादा flexible और clean बनता है
  • ✅ Maintain करना आसान होता है
  • ✅ Readability बढ़ती है

📌 Summary:

Feature Method Overloading Method Overriding
Timing Compile-time Run-time
Location Same Class Subclass
Parameters Different Same

🔚 Conclusion:

Java में Polymorphism एक important OOPs concept है जो हमें एक ही नाम के method को multiple तरीकों से use करने की flexibility देता है। यह program को ज्यादा readable, reusable और organized बनाता है।