package com.example.demo;
/**
* @Description 多态 对象类型转换
* @Auther guofeng.xie
* @Date 2020/1/2 21:15
*/
public class ClassCastTest {
public static void main(String[] args) {
/**
* 对象向上、向下转型问题
*/
Animal d = new Dog(); //自动向上转型
//此时的d编译器认为它是Animal,运行时JVM才会识别它是Dog。
animalShout(d); // 汪汪汪!
//d.seeDoor(); //这样写会报错,此时的d编译器认为它是Animal,
//而Animal并没有seeDoor()方法;若想使用Dog自己的方法需要强转回Dog。
Dog d2 = (Dog)d; //强制向下转型 在使用Dog自己的方法的时候需要转型回来。
d2.seeDoor();
/**
* 狗和猫互转的问题
*/
Animal c = new Cat();
Dog d3 = (Dog)c; //此时把猫强转为狗编译通过了
//(编译器编译时并不知道c的具体类型),但运行时就会报错:ClassCastException
d3.seeDoor(); //c强转为Dog后也可以使用seeDoor()方法
}
static void animalShout(Animal a) {
a.shout();
}
}
class Animal {
public void shout() {
System.out.println("叫了一声!");
}
}
class Dog extends Animal{
public void shout() {
System.out.println("汪汪汪!");
}
public void seeDoor() {
System.out.println("看门!");
}
}
class Cat extends Animal{
public void shout() {
System.out.println("喵喵喵!");
}
}
多态 对象类型转换
猜你喜欢
转载自blog.csdn.net/AlbenXie/article/details/103812146
今日推荐
周排行