创建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(); 



相关文章:

  • 2022-01-02
  • 2022-02-27
  • 2022-12-23
  • 2021-11-11
  • 2022-12-23
  • 2021-09-09
  • 2021-11-25
  • 2021-10-24
猜你喜欢
  • 2022-01-28
  • 2022-12-23
  • 2022-02-14
  • 2022-01-07
  • 2021-06-12
  • 2021-12-31
  • 2021-07-11
相关资源
相似解决方案