Java Tutorial-Java Polymorphism

Java Polymorphism


Polymorphism means “many forms”, and it occurs when we have many classes that are related to each other by inheritance.

Inheritance helps us to inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This means, we perform a single action in different ways.


Example


In the below example, we create two Java files, one file contains the main class and the other one contain the multiple classes with the Super class AnimalSound which contains the method animalSound(). Subclasses of AnimalSound are Dog, Cat and Cow. We can inherit AnimalSound class for many other animals in future such as Pig, Horse, etc.


AnimalSound.java

public class AnimalSound {
       public void animalSound(){
              System.out.println("Animal makes different sound");
       }
}

class Dog extends AnimalSound{
       public void animalSound(){
              System.out.println("Dog makes bow bow sound");
       }
}
 
class Cat extends AnimalSound{
       public void animalSound(){
              System.out.println("Cat makes meow meow sound");
       }
}
 
class Cow extends AnimalSound{
       public void animalSound(){
              System.out.println("Cow makes moo moo sound");
       }
}

AnimalSoundClass.java contains main class:

public class AnimalSoundClass {
       public static void main(String args[]){
              AnimalSound myAnimal = new AnimalSound();
              AnimalSound myDog = new Dog();
              AnimalSound myCat = new Cat();
              AnimalSound myCow = new Cow();
             
              myAnimal.animalSound();
              myDog.animalSound();
              myCat.animalSound();
              myCow.animalSound();
       }
}

Output

Animal makes different sound
Dog makes bow bow sound
Cat makes meow meow sound
Cow makes moo moo sound

Why and When to use “Inheritance” and “Polymorphism”?


It is mainly used for code reusability, reuse attributes and methods of an existing class when you create a new class.