博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
父类不能转换成子类
阅读量:5963 次
发布时间:2019-06-19

本文共 2114 字,大约阅读时间需要 7 分钟。

父类不能转换成子类

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()),虚拟机将抛一个运行时异常,因为你违反了约定的信任前提(你告诉编译器所有的都是正常的,但实际上并不是)

 

转载地址:http://pvjax.baihongyu.com/

你可能感兴趣的文章
git配置别名
查看>>
SpringMVC配置文件
查看>>
划分数系列问题
查看>>
springboot整合jersey
查看>>
Hibernate实体对象的生命周期(三种状态)
查看>>
23. Merge k Sorted Lists
查看>>
Python:pygame游戏编程之旅七(pygame基础知识讲解1)
查看>>
java B转换KB MB GB TB PB EB ZB
查看>>
通过SharpZipLib实现文件夹压缩以及解压
查看>>
20145209预备作业02
查看>>
精通CSS滤镜(filter)
查看>>
ios 中UIViewController的分类
查看>>
弄清楚高层到底是什么情况!
查看>>
开发中常用正则表达式
查看>>
HDU 4374 One hundred layer(单调队列DP)
查看>>
c和c++中NULL和0的区别
查看>>
OPP Services Log
查看>>
JQuery增删改查
查看>>
android webview 全屏播放H5 (Playing HTML5 video on fullscreen in android webview)
查看>>
python的一些常用函数
查看>>