Polymorphism is one of the fundamental principles of Object-Oriented Programming (OOP) that allows a single interface, method, or reference to represent different behaviors. It enables the same method call to produce different results depending on the object involved.
Key Points: • Polymorphism means "many forms," allowing objects to behave differently through a common interface. • Runtime Polymorphism is achieved through method overriding, where a subclass provides its own implementation of a parent class method. • Compile-time Polymorphism is achieved through method overloading, where multiple methods have the same name but different parameters. • It improves flexibility, extensibility, and maintainability of applications. • Polymorphism allows developers to write generic and reusable code.
Example: A Vehicle reference can point to different objects such as Car, Bike, or Bus. Calling the same start() method on each object can produce different behaviors based on the actual object type.
Code Example:
class Vehicle {
void start() {
System.out.println("Vehicle Started");
}
}
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car Started");
}
}
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Car();
vehicle.start();
}
}Interview Tip: A concise interview answer is:
"Polymorphism is the ability of a single interface or method to exhibit different behaviors based on the object it operates on. In Java, it is achieved through method overloading (compile-time polymorphism) and method overriding (runtime polymorphism)."