多态中的向上、向下转型
(老杜的Java基础班,Java个人学习笔记)
不管是向上转型还是向下转型,两个类之间必须有继承关系
一、向上转型:子 ––> 父
- Animal a = new Cat();
- 只能调用父类和子类共有的方法,返回子类方法的结果。
二、向上转型父 —>子
- Cat c = (Cat) a;
- 又称为强制类型转换,需要添加强制类型转换符
1、什么时候需要向下转型
- 需要调用或者执行子类对象中特有的方法
- 必须进行向下转型
2、向下转型又风险吗?
- 容易出现ClassCastException(类型传唤异常)
3、怎么避免这个风险?
- instanceof运算符,可以再程序运行阶段动态的判断某个引用的指向的对象是否为某一类型
- 养成好习惯,向下转型之前一定要使用instanceof运算符进行判断
// 举个栗子
// 下面是写好的动物类、猫类、鸟类
class Animal{
public void move(){
System.out.println("动物在移动!");
}
}
class Cat extends Animal{
// 覆盖move方法
public void move(){
System.out.println("猫在走猫步!!");
}
// 猫特有的方法
public void catchRat(){
System.out.prinln("猫在抓老鼠!!!");
}
}
class Bird extends Animal{
// 覆盖move方法
public void move(){
System.out.println("鸟儿在飞翔!");
}
// 鸟儿特有的方法
public void sing(){
System.out.println("鸟儿在唱歌!!!");
}
}
// 向上转型
public class Test01{
public static void main(String[] arge){
Animal c = new Cat();
Animal b = new Bird();
c.move();
b.move();
}
}
// 输出结果
/*
猫在走猫步!!
鸟儿在飞翔!
*/
// 向下转型
public class Test02{
public static void main(String[] args){
Animal a1 = new Cat();
Animal a2 = new Bird();
// 向下转型要加强制类型转换符
Cat c = (Cat)a1;
c.catchRat();
Bird b = (Bird)a2;
b.sing();
}
}
// 输出结果
/*
猫在抓老鼠!!!
鸟儿在唱歌!!!
*/
// 向下转型 instanceof 的使用
public class Test03{
public static void main(String[] args){
Animal a1 = new Cat();
Animal a2 = new Bird();
// 使用 instanceof 进行类型判断,判断引用指向的对象是否为某一类型
if (a1 instanceof Cat){
Cat c = (Cat)a1;
c.catchRat();
} else if (a1 instanceof Bird){
Bird b = (Bird)a1;
b.sing();
}
}
}