1. 引用类型的类型转换
1.1 向上转换(upcasting)子类对象可以直接当作父类对象使用,无需强制转换
1.2 向下转换(downcasting)
父类对象当作子类对象使用,需要强制类型转换,可能抛出异常
1.3 实例
public class Test {
public static void main(String[] args) {
// downcasting
Animal cat = new Cat();
//Cat c = (Cat)cat;
//c.run();
Dog d = (Dog)cat;
d.run();
/*
// upcasting
Cat cat = new Cat();
Animal a = cat;
//a.run();
Dog dog = new Dog();
Animal a1 = dog;
//a1.run();
Animal[] as = {a,a1};
for(int i=0;i<2;i++){
Animal ax = as[i];
ax.run();
}
*/
}
}
interface Animal{
public void run();
}
class Dog implements Animal{
@Override
public void run() {
System.out.println("dog run...");
}
}
class Cat implements Animal{
@Override
public void run() {
System.out.println("cat run...");
}
}
原文出处:http://geek99.com/node/431#
该博客教程视频地址:http://geek99.com/node/1627
转载于:https://blog.51cto.com/8785849/1413372