Method Polymorphism
Introduction to Method Polymorphism
Method polymorphism is a core concept in object-oriented programming that allows objects of different types to be treated uniformly while exhibiting unique behaviors.
Types of Polymorphism
graph TD
A[Method Polymorphism] --> B[Compile-time Polymorphism]
A --> C[Runtime Polymorphism]
B --> D[Method Overloading]
C --> E[Method Overriding]
Compile-time Polymorphism (Static Polymorphism)
Method Overloading
Methods with the same name but different parameters.
public class Calculator {
public int calculate(int a, int b) {
return a + b;
}
public double calculate(double a, double b) {
return a + b;
}
}
Runtime Polymorphism (Dynamic Polymorphism)
Method Overriding
Subclass provides a specific implementation of a method defined in its superclass.
abstract class Animal {
public abstract void makeSound();
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
Polymorphism Mechanisms
Inheritance-based Polymorphism
Concept |
Description |
Example |
Superclass Reference |
Parent class can reference child class objects |
Animal myPet = new Dog(); |
Method Dispatch |
Correct method implementation is selected at runtime |
myPet.makeSound() |
Polymorphic Method Invocation
public class PolymorphismDemo {
public static void demonstratePolymorphism() {
Animal[] animals = {new Dog(), new Cat()};
for (Animal animal : animals) {
animal.makeSound(); // Polymorphic method call
}
}
}
Advanced Polymorphism Techniques
Interface-based Polymorphism
interface Shape {
double calculateArea();
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
class Rectangle implements Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double calculateArea() {
return width * height;
}
}
Polymorphism Benefits
- Code flexibility
- Enhanced code reusability
- Simplified method invocation
- Support for dynamic behavior
Runtime Polymorphism Mechanism
graph TD
A[Method Call] --> B[JVM Determines Actual Method]
B --> C[Check Object's Actual Type]
C --> D[Invoke Corresponding Method Implementation]
Best Practices
- Use polymorphism to create more flexible designs
- Prefer interface-based polymorphism
- Follow the Liskov Substitution Principle
- Keep method signatures consistent
Potential Challenges
- Performance overhead
- Increased complexity
- Potential for misuse
Conclusion
Method polymorphism is a powerful technique that enables dynamic and flexible code design. LabEx recommends mastering these concepts to write more sophisticated Java applications.