父类不能转换成子类

父类不能转换成子类

Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to Boy
    at Test.main(Test.java:5)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

 

public class Test {

    public static void main(String[] args) {
        Person person = new Person();
        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");
    }
}

 

By using a cast you're essentially telling the compiler 
"trust me. I'm a professional, I know what I'm doing 
and I know that although you can't guarantee it, 
I'm telling you that this animal variable is definitely going to be a dog."
Since the animal isn't actually a dog (it's an animal, you could do Animal animal = new Dog(); 
and it'd be a dog) the VM throws an exception at runtime 
because you've violated that trust (you told the compiler everything would be ok and it's not!)

The compiler is a bit smarter than just blindly accepting everything, 
if you try and cast objects in different inheritence hierarchies (cast a Dog to a String for example) 
then the compiler will throw it back at you because it knows that could never possibly work.

Because you're essentially just stopping the compiler from complaining, 
every time you cast it's important to check that you won't cause a ClassCastException 
by using instanceof in an if statement (or something to that effect.)

https://stackoverflow.com/questions/4862960/explicit-casting-from-super-class-to-subclass

如果使用转型,你其实就是在告诉编译器:“请相信我,我是一个专家,我知道我在做什么虽然我并不能保证不出问题,我告诉你这个代表动物的变量肯定是一只狗。”
因为animal不一定就是一只dog(它是一只动物,如果这只动物是一只狗,你就可以进行这个操作Animal animal=new Dog()),虚拟机将抛一个运行时异常,因为你违反了约定的信任前提(你告诉编译器所有的都是正常的,但实际上并不是)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值