Polymorphism in Java-Object-Oriented Programming with exmple
Diagram of Polymorphism in Java-Object-Oriented Programming with exmple
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects to take many forms. In Java, polymorphism enables the same method name to behave differently based on context. There are two main types of polymorphism in Java:
Compile-time Polymorphism (Method Overloading)
Runtime Polymorphism (Method Overriding)
This article will explore both types of polymorphism with real-world examples to help you write flexible and reusable Java code.
Polymorphism comes from the Greek words poly (many) and morph (form). In Java, polymorphism allows methods to perform different tasks based on the object that invokes them or the number and type of arguments passed.
Method Overloading occurs when two or more methods in the same class have the same name but different parameters (number, order, or type of arguments).
public class Calculator {
// Overloaded add method
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
Happens at compile-time.
Improves code readability.
Same method name, but different method signatures.
Method Overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
Animal obj = new Dog();
obj.sound(); // Output: Dog barks
Happens at runtime.
Requires inheritance and use of the @Override
annotation.
Enables dynamic method dispatch.
Imagine building a payment system:
class Payment {
public void processPayment() {
System.out.println("Processing generic payment");
}
}
class CreditCardPayment extends Payment {
@Override
public void processPayment() {
System.out.println("Processing credit card payment");
}
}
class PayPalPayment extends Payment {
@Override
public void processPayment() {
System.out.println("Processing PayPal payment");
}
}
Using polymorphism:
Payment payment = new CreditCardPayment();
payment.processPayment(); // Output: Processing credit card payment
This approach lets you swap out payment types without changing the business logic.
Polymorphism is a powerful feature in Java that improves code clarity, flexibility, and maintainability. By understanding method overloading and method overriding, you can write more efficient object-oriented applications. Whether you're building a payment system or designing a game, leveraging polymorphism will help you structure your code better.