day10--对象的向上向下转型代码实现
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
package com.inmind.object_cast09;
|
||||
|
||||
public class Animal {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.inmind.object_cast09;
|
||||
|
||||
public class Cat extends Animal{
|
||||
|
||||
public void catchMouse(){
|
||||
System.out.println("猫在抓老鼠");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.inmind.object_cast09;
|
||||
/*
|
||||
向上转型:就是将子类赋值给父类,(多态的格式),非常安全直接写即可
|
||||
|
||||
向下转型是不安全的,原本是什么类型,那么只能转为该类型。(对象的强制类型转换,是有注意点的!)
|
||||
|
||||
对象的向上转型和向下转型:就是引用数据类型的类型转换
|
||||
|
||||
注意:多态的向下转型,一定要是对应的类型才能转换,否则就报ClassCastException(类型转换异常)
|
||||
*/
|
||||
public class Demo10 {
|
||||
public static void main(String[] args) {
|
||||
//使用多态来描述一只猫(父类引用指向子类对象)
|
||||
Animal animal = new Cat();//小范围的猫对象赋值给大范围的动物类型(安全的向上转型)
|
||||
|
||||
//将这个动物转为猫
|
||||
Cat cat = (Cat) animal;//大范围的动物对象赋值给小范围的猫类型(不安全的向下转型)
|
||||
cat.catchMouse();
|
||||
|
||||
//将这个动物转为狗
|
||||
Dog dog = (Dog) animal;//此处报出了java.lang.ClassCastException
|
||||
dog.watchDoor();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.inmind.object_cast09;
|
||||
|
||||
public class Dog extends Animal{
|
||||
|
||||
public void watchDoor(){
|
||||
System.out.println("狗在看门");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package com.inmind.poly08;
|
||||
/*
|
||||
多态的核心好处:“以不变,应万变”---通过抽象定义统一接口,应对具体实现的变化。它让代码简洁,灵活,更容易扩展。
|
||||
|
||||
|
||||
-----------------------------------------
|
||||
向上转型:就是将子类赋值给父类,(多态的格式),非常安全直接写即可
|
||||
*/
|
||||
public class Demo09 {
|
||||
public static void main(String[] args) {
|
||||
@@ -13,6 +17,9 @@ public class Demo09 {
|
||||
/*cat.run();
|
||||
cat.sleep();*/
|
||||
show(cat);
|
||||
//向上转型,是非常安全的,类似基本类型的自动转型
|
||||
Animal animal1 = dog;
|
||||
Animal animal2 = cat;
|
||||
}
|
||||
|
||||
//封装一个方法来调用动物跑和睡的行为
|
||||
|
||||
Reference in New Issue
Block a user