Polymorphism is a key concept in object-oriented programming that allows a single object to take on multiple forms. In Java, polymorphism is achieved through method overloading and method overriding.
Method overloading is a form of polymorphism where a class has multiple methods with the same name but different parameter lists. When you call an overloaded method, Java determines which version of the method to call based on the number, types, and order of the arguments that you pass in. Here’s an example of method overloading in Java:
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 that take different types of parameters. When you call the add()
method, Java will automatically choose the appropriate version of the method based on the type of arguments that you pass in.
Method overriding is another form of polymorphism where a subclass provides its own implementation of a method that is already defined in its superclass. When you call an overridden method, Java will choose the version of the method that is defined in the subclass, rather than the superclass. Here’s an example of method overriding in Java:
public class Animal {
public void makeSound() {
System.out.println("Animal is making a sound");
}
}
public class Dog extends Animal {
public void makeSound() {
System.out.println("Dog is barking");
}
}
In this example, the Animal
class has a makeSound()
method that prints a generic message. The Dog
class overrides this method with its own implementation that prints a message specific to dogs. When you call the makeSound()
method on a Dog
object, Java will call the version of the method that is defined in the Dog
class, rather than the Animal
class.
Polymorphism is a powerful concept in object-oriented programming that allows you to write more flexible, reusable, and extensible code. By using method overloading and method overriding effectively, you can create classes that are easier to use, maintain, and modify.