zoukankan      html  css  js  c++  java
  • 父类不能转换成子类

    父类不能转换成子类

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

  • 相关阅读:
    存储过程的优缺点?
    springboot注解
    springboot处理事务
    索引面试问题
    剑指Offer编程题(Java实现)——替换空格
    剑指Offer编程题(Java实现)——二维数组中的查找
    Java集合概括总结及集合选用
    Java中获取大小:length、length()、size()
    解决MarkDown打开出现:awesomium web-brower framework This view has crashed
    Java集合:Collection、List、Set、Map、泛型
  • 原文地址:https://www.cnblogs.com/softidea/p/5872636.html
Copyright © 2011-2022 走看看