繼承分級結構。在基礎類中,提供適用于所有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();?
}?
}?
}?