转自:http://blog.csdn.net/ld422586546/article/details/9707997

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,肯定不能成功。

上面的例子换句话来说,男孩和女孩都是人这肯定是对的,但你要说女孩是男孩肯定是不对的。

05-12 14:41