java 什么是多态性,什么是Java中的参数多态(带示例)?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值