Polymorphism is one of the core principles of Object-Oriented Programming (OOP) that allows a single interface, method, or reference to represent different forms of behavior. In Java, the same method call can produce different results depending on the actual object involved.
Key Points: • Polymorphism means "many forms," where one action can behave differently for different objects. • It improves flexibility, extensibility, and code reusability. • Java supports two types of polymorphism: Compile-Time Polymorphism and Runtime Polymorphism. • Method Overloading is an example of Compile-Time Polymorphism. • Method Overriding is an example of Runtime Polymorphism. • Polymorphism allows developers to write generic and maintainable code.
Example: Consider a Shape class with a draw() method. Different subclasses such as Circle and Rectangle can provide their own implementation of draw(). The same method call behaves differently depending on the object type.
Code Example:
class Shape {
void draw() {
System.out.println("Drawing Shape");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing Circle");
}
}
class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing Rectangle");
}
}
public class Demo {
public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();
shape1.draw();
shape2.draw();
}
}Output:
Drawing Circle Drawing Rectangle
Types of Polymorphism:
1. Compile-Time Polymorphism • Achieved through Method Overloading • Method selection happens during compilation
2. Runtime Polymorphism • Achieved through Method Overriding • Method selection happens at runtime based on the actual object type
Benefits of Polymorphism:
• Improves code flexibility • Promotes extensibility • Reduces code duplication • Supports loose coupling • Makes applications easier to maintain
Interview Tip: A concise interview answer is:
"Polymorphism is the ability of a single interface, method, or reference to represent different forms of behavior. In Java, the same method call can produce different results depending on the actual object being referenced. It is achieved through method overloading and method overriding."