Programming |
The process of performing multiple tasks with the single name is called as Polymorphism. By the help of inheritance we can provide multiple implementations for same method. Overloading and overriding help us achieve polymorphism in Java.
Program
class Animal { public void sound() { System.out.println("General sound of animals."); } } class Bear extends Animal { @Override public void sound() { System.out.println("Bear growling."); } } class Dog extends Animal { @Override public void sound() { System.out.println("Dogs barking."); } }
There are two types of Polymorphism:
Static polymorphism is implemented by using method overloading. Method overloading is a feature in which multiple methods are defined with same name but different parameters. The methods must have different number of arguments or/and different types of arguments. Depending on the parameters the compiler will verify which method will be called by the JVM.
Program
class Multiplication { double product(double x, double y) { return x * y; } int product(int x, int y) { return x * y; } int product(int x, int y, int z) { return x * y * z; } } public class StaticPolymorphism { public static void main(String[] args) { Multiplication multiplication = new Multiplication(); System.out.println("The product of 12.5 & 8.5 = " + multiplication.product(12.5, 8.5)); System.out.println("The product of 10 & 20 = " + multiplication.product(10, 20)); System.out.println("The product of 3, 5 & 9 = " + multiplication.product(3, 5, 9)); } }
Output
The product of 12.5 & 8.5 = 106.25 The product of 10 & 20 = 200 The product of 3, 5 & 9 = 135
2. Dynamic/Runtime polymorphism
Dynamic polymorphism is implemented by using dynamic dispatch and method overriding.
Program
class Animal { public void eat() { System.out.println("Animals Eating."); } } class Dog extends Animal { public void eat() { System.out.println("Dog eating treats."); } } class Cat extends Animal { public void eat() { System.out.println("Cats eating rats."); } } public class DynamicPolymorphism { public static void main(String[] args) { Animal animal = new Animal(); animal.eat(); Animal dog = new Dog(); dog.eat(); Animal cat = new Cat(); cat.eat(); } }
Output
Animals Eating. Dog eating treats. Cats eating rats.