Polymorphism is another fundamental principle of Object-Oriented Programming (OOP) in Java. It refers to the ability of an object to take on many forms or behaviors, depending on the context in which it is used.
In Java, polymorphism is achieved through two mechanisms: method overloading and method overriding.
Method Overloading: In method overloading, multiple methods can have the same name but different parameters. The compiler selects the appropriate method to call based on the number and types of arguments passed to the method. Here's an example:
public class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}
public int add(int num1, int num2, int num3) {
return num1 + num2 + num3;
}
}
In this example, the Calculator class has two methods named add, but with different numbers of parameters. When the add method is called with two arguments, the first version of the method is executed. When it is called with three arguments, the second version of the method is executed.
Method Overriding: In method overriding, a subclass provides a specific implementation of a method that is already provided by its parent class. Here's an example:
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("The cat meows");
}
}
In this example, the Animal class has a method named makeSound, which is overridden in the Dog and Cat classes to provide specific implementations for those classes. When the makeSound method is called on a Dog object, the Dog class's implementation of the method is executed, and when it is called on a Cat object, the Cat class's implementation of the method is executed.
Polymorphism allows us to write more flexible and reusable code by creating generic programming interfaces that can be implemented by many different classes in different ways. This can help reduce code duplication and improve the overall maintainability of the code.