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();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值