Question

I've tried to read through wikipedia but it's so dense on the subject of polymorphism (specifically related to Java). My understanding is subtype polymorphism is related to subtyping and parametric polymorphism is related to methods being generalized across different objects/classes? What am I missing?

Was it helpful?

Solution

As the article says,

Parametric polymorphism allows a function or a data type to be written generically, so that it can handle values identically without depending on their type ... Parametric polymorphism is also available in several object-oriented languages, where it often goes under the name "generics" (for example, Java) or "templates" (C++ and D)

So what this means (as an example) is you can make a function that takes a list of somethings, and the function can work no matter what those somethings are. Think of a method that returns the number of elements in a Collection. You can pass in a list of any type of elements, and it will return an answer. You don't have to rewrite the function for every kind of list you pass in.

Some languages employ the idea of subtyping to restrict the range of types that can be used in a particular case of polymorphism. In these languages, subtype polymorphism (sometimes referred to as inclusion polymorphism or dynamic polymorphism[citation needed]) allows a function to be written to take an object of a certain type T, but also work correctly if passed an object that belongs to a type S that is a subtype of T

In other words, you can have a method that takes an Animal as a parameter but you can also pass in a Cat or a Dog into it because Cats and Dogs are animals.

OTHER TIPS

You can find examples in JDK.

Example of parametric polymorphism:

public static <T> void sort(T[] a, Comparator<? super T> c) {
   ...
}

Method accepts any type T and can handle it identically:

Arrays.sort(new String[]{"a", "1"}, new Comparator<String>() { ... });

Example of subtype polymorphism:

Executors.newSingleThreadExecutor().submit(runable);

Here ExecutorService does not care about actual implementation of Runable, it just needs something it can run.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top