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 parametric polymorphism?
I believe it is since Animal.talk allows talk to be called despite the specific animal type (Cat or Dog).
public interface Animal
{
public String talk();
}
public class Cat implements Animal
{
public String talk()
{
return "Cat says Meow!";
}
}
public class Dog implements Animal
{
public String talk()
{
return "Dog says Woof! Woof!";
}
}
import java.util.*;
public class PolymorphismExample
{
public static void main(String[] args)
{
Collection animals = new ArrayList();
animals.add(new Cat());
animals.add(new Dog());
for (Animal a : animals)
{
System.out.println(a.talk());
}
}
}
Regards.
edit: if my example is not specifically exhibiting parametric polymorphism please would you provide one? thank you.
解决方案
"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 animals = new ArrayList();
A collection is specified to hold any object that is an animal.