The word polymorphism means having many forms. in simple words, we can define Java Polymorphism as the ability of a message to be displayed in more than one form.
Polymorphism is considered one of the most important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word "poly" means many and "morphs" means forms, that is the reason it is also called many forms.
In Java, polymorphism is achieved through two mechanisms :
Method Overloading
Method Overriding
Method Overloading:
Method overloading allows a class to have multiple methods of the same name but different parameters. The compiler determines which method to invoke based on the number and types of arguments passed. Method overloading is a form of compile-time polymorphism.
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;
}
}
Method Overriding:
Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This allows objects of the subclass to be treated as objects of the superclass. Method overriding is a form of run-time polymorphism.
Example of Method Overriding:
class Animal {
public void makeSound() {
System.out.println("animal sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Wauu!! Wauu!!");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!! Meow!!");
}
}
Comments