Java inheritance downcast ClassCastException

后端 未结 6 1373
走了就别回头了
走了就别回头了 2021-01-22 17:10

given the following code, I have a question:

class A{}
class B extends A {}
class C extends B{}

public class Test {
    public static void main(String[] args) {         


        
6条回答
  •  盖世英雄少女心
    2021-01-22 17:24

    You are trying to cast a super class reference variable to a sub class type. You cannot do this. Think practical, a super class object cannot contain independent methods (other than the super class' methods) of the sub class.

    At run-time you might call a method in the sub class which is certainly not in the super class object.

    class A{
      public void foo(){}
    }
    class B extends A {
      public void bar(){}
    }
    

    Now,

    A a=new A();
    B b=(B)a;
    b.bar();
    

    When you call like this the compiler, will only check whether the method bar() existed in the class B. That's it. It doesn't care about what is in the 'object' because it is created at runtime.

    But at runtime, as said before there is no bar() method in the object a. b is just a reference that is pointing to object a but a contains only foo() not bar()

    Hope you understood. Thank you.

提交回复
热议问题