day10-对象的向上向下转型代码实现
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
package com.inmind.object_cast10;
|
||||
|
||||
public abstract class Animal {
|
||||
public abstract void eat();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.inmind.object_cast10;
|
||||
|
||||
public class Cat extends Animal{
|
||||
@Override
|
||||
public void eat() {
|
||||
System.out.println("猫吃鱼");
|
||||
}
|
||||
public void catchMouse(){
|
||||
System.out.println("猫抓老鼠");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.inmind.object_cast10;
|
||||
/*
|
||||
对象的向上转型和向下转型:就是引用数据类型的类型转换
|
||||
|
||||
注意:多态的向下转型,一定要是对应的类型才能转换,否则就报ClassCastException(类型转换异常)
|
||||
*/
|
||||
public class Demo10 {
|
||||
public static void main(String[] args) {
|
||||
//多态,来一只猫
|
||||
//父类引用指向子类对象(多态)
|
||||
Animal animal = new Cat();//向上转型
|
||||
animal.eat();//编译时看左边,运行时看右边
|
||||
//我就要这个动物,抓老鼠(把它转成猫再抓老鼠)
|
||||
Cat cat = (Cat) animal;//向下转型
|
||||
cat.catchMouse();
|
||||
|
||||
//我就要这个动物,看门(把它转成狗再看门)
|
||||
Dog dog = (Dog) animal;//报错,此时animal引用的是Cat对象,无法转成Dog对象,会出现java.lang.ClassCastException
|
||||
dog.lookHome();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.inmind.object_cast10;
|
||||
|
||||
public class Dog extends Animal{
|
||||
@Override
|
||||
public void eat() {
|
||||
System.out.println("狗吃骨头");
|
||||
}
|
||||
|
||||
public void lookHome(){
|
||||
System.out.println("狗看家");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user