• 父类不能转换成子类


    父类不能转换成子类

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

  • 相关阅读:
    Tomcat 容器的安全认证和鉴权
    Tomcat 中的 Session 和 Cookie
    Tomcat 类加载器的实现
    Tomcat 对静态资源的处理
    Tomcat 路由请求的实现 Mapper
    Tomcat 配置文件解析工具 Digester
    Tomcat 容器的设计和实现
    ArrayList 和 LinkedList 源码分析
    Mybatis自定义分布式二级缓存实现与遇到的一些问题解决方案!
    Dubbo序列化多个CopyOnWriteArrayList对象变成同一对象的一个大坑!!
  • 原文地址:https://www.cnblogs.com/softidea/p/5872636.html
Copyright © 2020-2023  润新知