1.Animal,Cat,Bird三个类之间的关系:
- Cat继承Animal
- Bird继承Animal
- Cat和Bird之间没有任何的继承关系
2.关于多态中涉及到的几个概念:
-
向上转型 (upcasting)
- 子类型 -->父类型 又被称为:自动类型转换
- 向下转型(downcasting)
-
向下转型(downcasting)
- 父类型 -->子类型 又被称为:强制类型转换【需要加强制类型转换符】
3.需要记忆:
无论是向上转型还是向下转型,两种类型之间必须要有继承关系
没有继承关系,程序时无法编译通过的。
示例代码:
public class Test { public static void main(String[] args) { //以往的对象创建方式 Animal a1 = new Animal(); a1.move(); Cat c1 = new Cat(); c1.move(); c1.CatCatch(); Bird b1 = new Bird(); b1.move(); //多态的方式创建 Animal a2 = new Cat(); a2.move(); //a2.Catch();编译报错。 Cat c2 = (Cat)a2; c2.move(); c2.CatCatch();//猫抓老鼠 //父类型引用指向子类型对象【多态】 Animal a3 = new Bird(); //Cat c3 = (Cat)a3; if(a3 instanceof Bird){//a3是一个Bird类型的对象 Bird b2 = (Bird)a3; b2.move(); b2.fly(); }else if(a3 instanceof Cat){//a3是一个Cat类型的对象 Cat c3 = (Cat)a3; c3.move(); c3.CatCatch(); } } } class Animal { public void move(){ System.out.println("动物在移动!"); } } class Bird extends Animal { public void move() { System.out.println("鸟儿会飞翔!"); } //子类特有事物行为/动作 public void fly() { System.out.println("Bird Fly!"); } } class Cat extends Animal { //重写父类中继承过来的方法 public void move() { System.out.println("猫在走猫步!"); } //不是父类中继承的方法 //这个方法是子类对象特有的行为【不是说所有的动物都能抓老鼠!】 public void CatCatch(){ System.out.println("猫会抓老鼠!"); } }