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 the objects of a common Base Class. In Java, polymorphism is achieved through;

  • Method Overriding
  • 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.


polymorphism.java
class Animal {
  void makeSound() {
    System.out.println("Animal makes a sound.");
  }
}

class Dog extends Animal {
  @Override
  void makeSound() {
    System.out.println("Dog barks.");
  }
}

class Cat extends Animal {
  @Override
  void makeSound() {
    System.out.println("Cat meows.");
  }
}

public class Main {
  public static void main(String[] args) {
    Animal myAnimal1 = new Dog();
    Animal myAnimal2 = new Cat();

    myAnimal1.makeSound();
    myAnimal2.makeSound(); 
  }
}

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.

polymorphism.java
class Animal {
  void makeSound() {
    System.out.println("Animal makes a sound.");
  }
}

class Dog extends Animal {
  @Override
  void makeSound() {
    System.out.println("Dog barks.");
  }
}

class Cat extends Animal {
  @Override
  void makeSound() {
    System.out.println("Cat meows.");
  }
}

public class Main {
  public static void main(String[] args) {
    Animal myAnimal1 = new Dog();
    Animal myAnimal2 = new Cat();

    myAnimal1.makeSound();
    myAnimal2.makeSound(); 
  }
}

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.