Polymorphism in Java
What is Polymorphism?
Polymorphism in Java means "many forms".
It allows the same method or interface to work differently depending on the object that invokes it.
It supports method overloading (compile-time polymorphism) and method overriding (runtime polymorphism).
Java में Polymorphism का मतलब है "many forms" यानी एक interface कई रूपों में काम कर सकता है।
इसमें एक ही method या interface अलग-अलग objects के हिसाब से अलग तरह से काम करता है।
इसमें compile-time polymorphism (method overloading) और runtime polymorphism (method overriding) आते हैं।
Advantages of Polymorphism
- Improves code flexibility and reusability.
- Supports abstraction and loose coupling.
- Allows new functionality without changing existing code.
- Enhances code readability and maintenance.
- Code को flexible और reuse करना आसान बनाता है।
- Abstraction और loose coupling को support करता है।
- Existing code को बदले बिना नई functionality जोड़ सकते हैं।
- Code पढ़ने और maintain करने में आसान होता है।
Example: Employee Class using Polymorphism
Here we demonstrate runtime polymorphism using method overriding. The Employee
class has a work()
method. Subclasses Manager
and Developer
override it to provide specific implementations.
इस उदाहरण में हम runtime polymorphism method overriding के ज़रिये दिखाते हैं। Employee
class में work()
method है जिसे Manager
और Developer
subclasses override करते हैं।
class Employee {
void work() {
System.out.println("Employee working...");
}
}
class Manager extends Employee {
void work() {
System.out.println("Manager managing team and projects.");
}
}
class Developer extends Employee {
void work() {
System.out.println("Developer writing and debugging code.");
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
Employee e;
e = new Employee();
e.work();
e = new Manager();
e.work();
e = new Developer();
e.work();
}
}
Output:
Employee working... Manager managing team and projects. Developer writing and debugging code.
In this example, the work()
method behaves differently depending on the object type, demonstrating runtime polymorphism in Java.
इस उदाहरण में work()
method अलग-अलग objects के हिसाब से अलग तरह से काम करता है। यह Java में runtime polymorphism को दर्शाता है।