向上类型转换(自动类型转换)
只能调用父类中存在的方法,或者是重写的方法
在子类中定义的方法将不能使用
- 父类引用=子类对象 自动转换
- 调用的子类继承的方法
- 调用的是子类重写的方法
- 不能调用子类特有的方法
public class TestPoly2 {
public static void main(String[] args) {
//基本数据类型的类型转换
int n = 5;
System.out.println(n);
double d = n;
System.out.println(d);
//double d2 = 5;//自动转换 double>int
//引用数据类型的类型转换
Programmer ch = new English();//自动转换 父类引用=子类对象
ch.eat();
ch.work();
//ch.raceHorse();
}
}
向下类型转换(强制类型转换)
** int a=(int)9.8; 基本数据类型的强制转换**
- 向下转型后就可以调用子类特有的方法了
- 不是做手术,必须转换成真实子类型,否则ClassCastException:
- 向下转型之前肯定发生了向上转型 正确
- 为了避免ClassCastException,向下转型之前先判断一下instancof
public class TestPoly3 {
public static void main(String[] args) {
//基本数据类型的类型转换
double d = 3.14;
System.out.println(d);
int n = (int)d;// 强制转换 int < double 做手术
System.out.println(n);
//引用数据类型的类型转换
Programmer pro = new English();
pro.work();
pro.eat();
//pro.playShadowBoxing();
//如果想调用特有的方法,向上之后再向下转型即可
//Chinese ch = (Chinese)pro;//不是做手术,必须转换成真实子类型
//Dog dog = (Dog)obj;
//ch.playShadowBoxing();
if(pro instanceof Chinese){
Chinese ch = (Chinese)pro;
ch.playShadowBoxing();
}else if(pro instanceof English){
English en = (English) pro;
en.raceHorse();
}else if(pro instanceof Italian){
Italian it = (Italian)pro;
it.playFootBall();
}
pro = new English();
System.out.println(pro instanceof Object);//true
System.out.println(pro instanceof Programmer);//true
System.out.println(pro instanceof English);//true
System.out.println(pro instanceof Chinese);//false
//System.out.println(pro instanceof String);//不允许比较 编译错误
}
}