What is parametric polymorphism in Java (with example)?

后端 未结 3 604
温柔的废话
温柔的废话 2021-02-07 07:18

It is my understanding that parametric polymorphism is a technique which allows uniform actions over a variety of data(types). Is my knowledge correct?

Is this example p

相关标签:
3条回答
  • 2021-02-07 08:03

    "Parametric Polymorphism" is just another term for "Generics" in Java. The idea is simple: you state what types will be used by a particular class, a clear example of this is present in all the collections of the java.util package.

    For learning all the nuances of generics in Java, I highly recommend Angelika Langer's FAQ, it explores every corner of the specification.

    In your code, this line is an example of using generics:

    Collection<Animal> animals = new ArrayList<Animal>();
    

    A collection is specified to hold any object that is an animal.

    0 讨论(0)
  • 2021-02-07 08:04

    Precisely. Parametric polymorphism generally refers to generics/templates.

    From wikipedia:

    Using parametric polymorphism, a function or a data type can be written generically so that it can handle values identically without depending on their type.

    0 讨论(0)
  • 2021-02-07 08:06

    Wikipedia:

    In programming languages and type theory, parametric polymorphism is a way to make a language more expressive, while still maintaining full static type-safety. Using parametric polymorphism, a function or a data type can be written generically so that it can handle values identically without depending on their type. Such functions and data types are called generic functions and generic datatypes respectively and form the basis of generic programming.

    So a great example is the standard Java library collections.

    For example, Collections.sort is declared as:

    public static <T extends Comparable<? super T>> void sort(List<T> list)
    

    It can take a list of objects of type T that is comparable to other T's and sort the list, without worrying about what type T actually is.

    It is different from subtype polymorphism: subtype polymorphism is exemplified by the fact that sort can take any sort of List -- an ArrayList, a LinkedList, etc.

    0 讨论(0)
提交回复
热议问题