Polymorphism – Define In Just Two Sentences-Collection of common programming errors
Just thought I’d add my own interpretation of what polymorphism is: very generically, polymorphism is the act of providing a single interface to entities of different types.
That’s rather generic, but that’s the only way I can think of to wrap all three types of polymorphisms I know about: ad hoc, parametric and subtype. I’ll go in more details below, and have sorted polymorphism types by name, alphabetically. The one you’re interested on is most probably subtype polymorphism, which is the last one.
ad hoc polymorphism
ad hoc polymorphism is the act of providing multiple implementations of the same method for different parameter types. In OOP, it’s generally known as method overloading. For example:
public String format(int a) {
return String.format("%2d", a);
}
public String format(Date a) {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(a);
}
Both format methods share a single interface but work on entities of different types.
Parametric polymorphism
Parametric polymorphism is the act of making a class (or method) work on a type that is itself a parameter of the class (or method). It’s often referred to as generics.
For example, Java’s List[T] expects a parameter T at instantiation time, and this parameter defines the type of the resulting object.
Note for purists that I’m purposefully ignoring raw types as I feel they’d just muddy the waters in this context.
List[String] and List[Date] share a single interface, but work on (and are) different types.
Subtype polymorphism
Subtype polymorphism is probably what you initially meant in your question: it’s the act of providing a single interface to multiple implementations of the same type.
To use the customary example: Animal provides a contract that all implementations must respect. Dog is an Animal, and as such supports all operations that Animal declares. According to the Liskov substitution principle, this allows you to use an instance of Dog where an instance of Animal is expected (but not the other way around).
If Cat and Dog are both subclasses of Animal, then they share a single interface but are in fact different types.
I’m going off in a bit of a tangent here, but subtype polymorphism is (I think) the only one that allows overriding: the act of redefining the behaviour of a method defined by a parent class. This is often confused with overloading which, as we saw before, is a type of polymorphism and doesn’t in fact need subclassing (nor does it need classes, really).