什么是Java中的参数多态(带示例)? [英] What is parametric polymorphism in Java (with example)?
问题描述
据我所知,参数多态是一种允许对各种数据(类型)进行统一操作的技术。我的知识是否正确?
It is my understanding that parametric polymorphism is a technique which allows uniform actions over a variety of data(types). Is my knowledge correct?
这个示例是参数多态吗?
我相信是因为Animal.talk允许调用谈话,尽管特定的动物类型(猫或狗)。
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<Animal> animals = new ArrayList<Animal>();
animals.add(new Cat());
animals.add(new Dog());
for (Animal a : animals)
{
System.out.println(a.talk());
}
}
}
问候。
编辑:如果我的例子没有具体展示参数多态性,请你提供一个?谢谢。
edit: if my example is not specifically exhibiting parametric polymorphism please would you provide one? thank you.
推荐答案
参数多态只是Java中泛型的另一个术语。这个想法很简单:你说明一个特定类将使用 types ,这个的明显例子出现在 java.util $ c的所有集合中$ c> package。
"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.
为了学习Java中泛型的所有细微差别,我强烈推荐Angelika Langer的常见问题解答,它探讨了规范的每个角落。
For learning all the nuances of generics in Java, I highly recommend Angelika Langer's FAQ, it explores every corner of the specification.
在您的代码中,这一行是使用泛型的一个例子: / p>
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.
这篇关于什么是Java中的参数多态(带示例)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!