Javain,java in think 多態問題

 2023-10-21 阅读 20 评论 0

摘要:創建Rodent(嚙齒動物):Mouse(老鼠),Gerbil(鼴鼠),Hamster(大頰鼠)等的的一個?繼承分級結構。在基礎類中,提供適用于所有Rodent的方法,并在衍生類中覆蓋它們,從而根據不同
創建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();?
}?
}?
}?

Javain,轉載于:https://www.cnblogs.com/JPAORM/archive/2012/05/19/2510288.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/154198.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息