Polymorphism

Polymorphism means "many shapes" and refers to the ability of objects to take on multiple forms.

Polymorphism is one of the fundamental concepts of object-oriented programming (OOP). It allows objects of different classes to be treated as objects of a common Parent Class. In Java, polymorphism is achieved through;

  1. Method Overriding
  2. Interfaces

Polymorphism with Method Overriding

It occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. To override a method, you use the @Override annotation to indicate that a method in the subclass is intended to override a method in the superclass.

In this example, we'll create a superclass Animal with a method makeSound(), and then we'll create two subclasses, Dog and Cat, that override the makeSound() method.

In this example;

  • Animal is the superclass with a makeSound() method.
  • Dog and Cat are subclasses of Animal that override the makeSound() method with their specific implementations.
  • In the Main class, we create objects of both Dog and Cat and assign them to references of type Animal. When we call makeSound() on these references, it invokes the overridden methods in the respective subclasses, demonstrating polymorphic behavior.

Polymorphism with Interfaces

In this example, we'll define an interface Sound with a makeSound() method, and then we'll create classes Dog and Cat that implement the Sound interface.

In this example;

  • Sound is an interface with a makeSound() method.
  • Dog and Cat are classes that implement the Sound interface and provide their own implementations of the makeSound() method.
  • In the Main class, we create objects of both Dog and Cat and assign them to references of type Sound. When we call makeSound() on these references, it invokes the methods implemented in the respective classes, demonstrating polymorphism through interfaces.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min