Java Polymorphism


Java Polymorphism

Polymorphism means "many kinds", and it happens when we have many categories related to each other by inheritance.

As we mentioned in the preceding chapter; Inheritance allows us to acquire qualities and methods from another category. Polymorphism uses such methods to perform various functions. This allows us to perform the same action in different ways.

For example, consider the superclass called Animal with a method called animalSound(). Sub-categories of Animals can be Pigs, Cats, Dogs, Birds - They also have their own use of animal sounds (pig oinks, and cat meows, etc.):


Example
class Animal {
            public void animalSound() {
              System.out.println("The animal makes a sound");
            }
          }
          
          class Pig extends Animal {
            public void animalSound() {
              System.out.println("The pig says: wee wee");
            }
          }
          
          class Dog extends Animal {
            public void animalSound() {
              System.out.println("The dog says: bow wow");
            }
          }
          

Remember from the Properties chapter that we use an extended keyword to gain a class inheritance.


We can now create Pig and Dog items and call the animalSound() in both:


Example
class Animal {
            public void animalSound() {
              System.out.println("The animal makes a sound");
            }
          }
          
          class Pig extends Animal {
            public void animalSound() {
              System.out.println("The pig says: wee wee");
            }
          }
          
          class Dog extends Animal {
            public void animalSound() {
              System.out.println("The dog says: bow wow");
            }
          }
          
          class Main {
            public static void main(String[] args) {
              Animal myAnimal = new Animal();  // Create a Animal object
              Animal myPig = new Pig();  // Create a Pig object
              Animal myDog = new Dog();  // Create a Dog object
              myAnimal.animalSound();
              myPig.animalSound();
              myDog.animalSound();
            }
          }
          

Why And When To Use "Inheritance" and "Polymorphism"?

- Useful for code reuse: re-use the attributes and methods of the existing class when creating a new class.