Polymorphism

Polymorphism is an object oriented term that is used to describe the implementation of a single interface to multiple objects. The three different types of polymorphism are: ad hoc polymorphism, parametric polymorphism, and subtype polymorphism(AKA inclusion polymorphism).

Ad Hoc Polymorphism

Ad Hoc Polmorphism occurs when the same operation or method behave differently depending on the data types that are passed as arguments.

Example:

5 + 5 = 10;
"Hello" + "World" = "HelloWorld";

This demonstrates how the addition operator is polymorphic because when using integers, it performs an addition, and when using Strings, it performs a concatenation–two different operations for two different data types using the same operator.

Parametric Polymorphism

Parametric polymorphism occurs when an interface can be adapted to different data types or methods through the use of Generics.

Example:

ArrayList list = new ArrayList;
Typically, one would use “” to specific the collection’s datatype, yet in this polymorphic case, it is unnecessary. ArrayList can be used for any data type given the Generic declaration is appropriate; hence, only one interface is being used for many different types of objects because of this generic implementation.

Subtyping

Subtype Polymorphism occurs when an interface limits the amount of polymorphic types that can be used, and is typically implemented via abstract object methods.

Example:

abstract class Animal {
 abstract String noise();
}
class Dog extends Animal {
 public String noise() {
  return "Bark";
 }
}
class Cat extends extends {
 public String noise() {
  return "Meow";
 }
}
public class Runner {
 public void makeNoise(Animal a) {
  System.out.print(a.noise());
 }
 public static void main(String[] args) {
  makeNoise(new Cat());
  makeNoise(new Dog());
 }
}

In this example, the Dog will output Bark while the Cat will output Meow. This demonstrates subtype polymorphism because the parent Animal type will be differentiated based on subtype implementations.