`
tangzlboy
  • 浏览: 88643 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

think in java 多态问题

 
阅读更多
创建Rodent(啮齿动物):Mouse(老鼠),Gerbil(鼹鼠),Hamster(大颊鼠)等的的一个
继承分级结构。在基础类中,提供适用于所有Rodent的方法,并在衍生类中覆盖它们,从而根据不同类型的Rodent采取不同的行动。创建一个Rodent数组,在其中填充不同类型的Rodent,然后调用自己的基础类方法,看看会有什么情况发生。

解决方法:
package com.tangle.polymorphic;
class Rodent {
void nightAction(){
System.out.println("Rodent.neghtAction()");
}
}
class Mouse extends Rodent {
void nightAction(){
System.out.println("Mouse.nightAction()");
}
}
class Gerbil extends Rodent {
void nightAction(){
System.out.println("Gerbil.nightAction()");
}
}
class Hamster extends Rodent {
void nightAction(){
System.out.println("Hamster.nightAction()");
}
}
public class RodentTest {
public static void main(String[] args) {
Rodent[] rt = new Rodent[4];
rt[0] = new Rodent();
rt[1] = new Mouse();
rt[2] = new Gerbil();
rt[3] = new Hamster();
for (Rodent rodent : rt) {
rodent.nightAction();
}
}
}
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics