向上转型与向下转型
向上转型
1.首先准备两个类:
Animal类
public class Animal {
String name = "动物";
public void sleep(){
System.out.println("睡");
}
public void run(){
System.out.println("跑");
}
public void eat(){
System.out.println("吃");
}
public void show(){
System.out.println("看");
}
}
Cat类,继承了Animal类
public class Cat extends Animal {
public void eat(){//方法重写
System.out.println("猫吃鱼");
}
public void catchMouse(){
System.out.println("猫抓老鼠");
}
}
2.使用Polydetail类来说明向上转型问题
public class Polydetail {
public static void main(String[] args) {
//向上转型:父类的引用指向子类的对象
//语法:父类类型引用名 = new 子类类型()
// 左边是:编译类型 , 右边是:运行类型
Animal animal = new Cat();
//1.可以调用父类中所有的成员(需遵守访问权限)
//2.不能调用子类中的特有成员
//animal.catchMouse() 直接出错,因为在编译阶段,能调用哪些成员,是由编译类型来决定的(看编译类型)
//3.最终运行效果看子类的具体实现(看运行类型)
animal.eat();//"猫吃鱼" 看运行类型,即Cat()类中是否有eat()方法,有直接则直接调用,没有则在父类中找是否有,没有则找父类的父类中是否有......
animal.run();//"跑" 运行类型Cat()中没有,找的是Animal()中的run()方法
}
}
向下转型
public class Polydetail2 {
public static void main(String[] args) {
Animal animal = new Cat();
//按照上面Polydetail类中的写法
//现在希望调用Cat的 catchMouse方法,所以得使用向下转型
//1.语法:子类类型 引用名 = (子类类型)父类引用
Cat cat = (Cat) animal;
//此时cat 的编译类型是 Cat,运行类型是 Cat
cat.catchMouse();//"猫抓老鼠"
//2.要求父类的引用必须指向的是当前目标类型的对象
//Dog dog = (Dog) animal; 编译可以通过,但是会抛出ClassCastException异常,因为Dog类和Cat类根本就没有关系,dog是无法引用当前的这个Cat()对象
}
}
class Dog{
}
一张图解释一下上面的第二点内容:要求父类的引用必须指向的是当前目标类型的对象