Polymorphism in Java refers to the ability of a method or object to take on many forms. It allows the same method name to behave differently based on the context, improving code flexibility and reusability.
In Java, polymorphism can be achieved in two main ways:
Runtime Polymorphism (Method Overriding):
This happens when a subclass provides a specific implementation of a method already defined in its superclass. The decision about which method to call is made at runtime, allowing dynamic method dispatch.
Compile-time Polymorphism (Method Overloading):
This occurs when multiple methods in the same class have the same name but differ in the number or type of parameters. The method to be executed is determined at compile time.
Method Overriding:
Overriding in Java is a key feature of runtime polymorphism and is achieved through inheritance. When a class extends another class using the extends keyword, it inherits the methods of the superclass. The subclass can then provide its own implementation of those methods, which is known as method overriding.
In method overriding:
The overridden method in the subclass is called at runtime, based on the object type.
The method in the subclass must have the same name, return type, and parameters as the method in the superclass.
public class BaseClass{
public void setUp(){
System.out.println(“Implementation from super class”);
}
}
public class ChildClass() extends BaseClass{
@override
public void setUp(){
System.out.print(“Implementation from subclass”);
}
}
public class Main {
public static void main(String[] args) {
BaseClass obj = new ChildClass();
obj.setUp(); // Output: ChildClass setup
}
}
Method Overloading:
Method Overloading is a form of compile-time polymorphism in Java. It allows you to define multiple methods with the same name in the same class, as long as they have different parameter lists (i.e., different number or type of parameters).
This enables you to use the same method name to perform different tasks based on the type or number of arguments passed.
Key Points:
Return type can be different but is not sufficient alone to overload a method.
Methods must have the same name.
They must differ in the number or type of parameters.
Example: Calculating Area with Method Overloading
public class AreaCalculator {
// Area of rectangle (int)
int area(int length, int width) {
return length * width;
}
// Area of rectangle (float)
float area(float length, float width) {
return length * width;
}
// Area of cuboid (int)
int area(int length, int width, int height) {
return length * width * height;
}
public static void main(String[] args) {
AreaCalculator calc = new AreaCalculator();
System.out.println("Area (int): " + calc.area(5, 4)); // Rectangle with int
System.out.println("Area (float): " + calc.area(5.5f, 4.2f)); // Rectangle with float
System.out.println("Volume: " + calc.area(3, 4, 5)); // Cuboid with int
}
}