day10-对象的向上向下转型代码实现
This commit is contained in:
@@ -28,6 +28,10 @@ Person p = new Student();//这里才使用了多态
|
||||
|
||||
一定要注意:编译看左边,运行看右边。
|
||||
多态中:代码的书写时,父类中没有的变量和方法是不能写的,因为编译看左边,编译器会直接报错
|
||||
|
||||
多态的核心好处:“以不变,应万变”---通过抽象定义统一接口,应对具体实现的变化。它让代码简洁,灵活,更
|
||||
容易扩展。
|
||||
|
||||
*/
|
||||
public class Demo09 {
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -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