说实话真的挺绕的。。。
/*
*
* 一个子类对象的类型可以向上转换成父类类型,即子类对象可以当作父类对象使用
* 这种转换是安全的,叫做自动类型转换
* 而一个父类对象类型一般是不能转换为子类对象使用的。因为子类继承与父类,所以说子类中的
* 一些数据成员和方法父类中未必会有,但如果是一个父类对象引用实际引用的是一个子类对象,
* 则可以强制将这个父类对象引用转换成子类对象
*
* */
class GrandS extends Father{
public static void main(String[] args){
// a1是父亲对象的引用,a2是孙子类对象的引用
GrandF a1 = new Father();
GrandF a2 = new GrandS();
// 强制类型转换,不要看是对象的引用属于那个类,要看其引用的对象是否是将转换成的类的子类或‘本’类
Father b1 = (Father) a1;
Father b2 = (Father) a2;
// GrandS c1 = (GrandS) a1; // 这个相当于是turn Father to GrandS,父类转为子类则不能够实现
GrandS c2 = (GrandS) a2;
// 通过instanceof函数来判断某一个对象的实际类型是否属于某一个指定类或派生于指定类的.
if(b1 instanceof GrandF) System.out.println("b1 belongs GrandF");
if(a1 instanceof Father) System.out.println("a1 belongs Father");
if(a1 instanceof GrandS) System.out.println("a1 belongs GrandS");
else System.out.println("a1 does not belong GrandS");
if(a2 instanceof GrandS) System.out.println("a2 belongs GrandS");
if(c2 instanceof GrandF) System.out.println("c2 belongs GrandF");
}
}
class Father extends GrandF {
}
class GrandF {
}