Polymorphism is the ability of an object to take on many forms. In Java, polymorphism is implemented through two mechanisms: method overloading and method overriding.
Method overloading is when a class has two or more methods with the same name, but with different parameters. The Java compiler determines which method to call based on the number, types, and order of the parameters passed in. Here’s an example of method overloading:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
In this example, the Calculator class has two add methods with different parameter types. One method takes two integers, and the other takes two doubles. When you call the add method with two integers, the first method will be called. When you call the add method with two doubles, the second method will be called.
Method overriding is when a child class provides its own implementation of a method that is already defined in the parent class. The child class must use the @Override annotation to indicate that it is overriding a method from the parent class. Here’s an example of method overriding:
public class Animal {
public void makeSound() {
System.out.println("The animal is making a sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog is barking");
}
}
In this example, the Animal class has a makeSound method that prints a message. The Dog class overrides this method and provides its own implementation that prints a different message. When you call the makeSound method on an object of the Dog class, the overridden method in the child class will be called instead of the method in the parent class.
Polymorphism allows you to write more flexible and reusable code. By using method overloading and method overriding, you can write methods that can accept different types of parameters and have different behavior depending on the context in which they are called. Polymorphism is a key concept in Java and is essential to writing object-oriented programs in Java.