package jiCheng_duoTai;
public class QZZH {//强制转换
//Java中强制转换成子类的原则:父亲型的引用指向的是哪个子类的实例,就能转换成哪个子类的引用。
public static void main(String[] args) {
Person pe = new Boy();//将父类的引用指向Boy,将开辟的Boy地址赋给pe
Boy boy = (Boy) pe ;//强制转换:将pe强制转换为Boy类的对象
boy.eat();
// pe.eat();
Person e = new Girl();
Girl girl = (Girl)e;
girl.eat();
// e.eat();
Person per = new Girl();
// Boy b =(Girl)per;//报错语句
}
}
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 ");
}
}
class Girl extends Person{
public void eat() {
System.out.println(" The girl were eating ");
}
}
打印结果: The Boy were eating
原因:当Boy实例化后将引用地址返回传给pe,这是pe引用实际指向的是Boy,所以将pe转换成Boy能成功
若在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,肯定不能成功
简单的理解就是男孩女孩都是人没错,但是说女孩是男孩就错了