java in think 多态问题

来源:互联网 发布:异星工厂修改数据 编辑:程序博客网 时间:2024/04/26 01:36
创建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(); 



原创粉丝点击