Java中父類強制轉換成子類的原則:父類型的引用指向的是哪個子類的實例,就能轉換成哪個子類的引用。
例:
public class Test {
public static void main(String[] args) {
Person person = new Boy();
Boy boy = (Boy) person;
boy.eat();
}
}
class Person {
public void eat() {
System.out.println("The people were eating");
}
}
class Boy extends Person {
public void eat() {
System.out.println("The boy were eating");
}
}
打印結果:The boy were eating
原因:當Boy實例化后將引用地址返回傳給person,這時person引用實際指向的是Boy,所以將person轉換成Boy能成功。
再定義一個類:
class Girl extends Person {
public void eat() {
System.out.println("The girl were eating");
}
}
main方法中添加:
Person p = new Girl();
Boy b = (Boy)p;
b.eat();
運行時提示:Girl cannot be cast to Boy(不能將女孩轉換成男孩)
原因:當Girl實例化后將引用地址返回傳給p,這時p引用實際指向的是Girl,將p轉換成Boy也就是說將Girl轉換成Boy,肯定不能成功。
上面的例子換句話來說,男孩和女孩都是人這肯定是對的,但你要說女孩是男孩肯定是不對的。
父類轉子類的前提是:此父類對象為子類對象的引用
例如:
Father father = (Father)son;
當這種情況時,可以用instanceof判斷是否是子類類型(實際) 然后強轉回去
if(father instanceof Son)
Son son =(Son)father;
除此之外,不行。