Polymorphism, derived from “many forms,” arises when multiple classes are interconnected through inheritance.
As mentioned in the preceding chapter, Inheritance facilitates the acquisition of attributes and methods from another class. Polymorphism leverages these methods to execute diverse tasks, enabling the execution of a singular action through various approaches.
Consider a superclass named Animal containing a method called animalSound(). Subclasses of Animal, such as Pigs, Cats, Dogs, and Birds, possess their unique implementations of animal sounds (for instance, pigs oink and cats meow).
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"); } |
Recall from the Inheritance chapter that we use the extends keyword to inherit from a class. |
Now, we have the capability to instantiate Pig and Dog objects and invoke the animalSound() method on each of them:
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”?It facilitates code reusability by allowing you to utilize the attributes and methods of an existing class when defining a new class. |