why can not access child fields using parent reference

后端 未结 6 1847
耶瑟儿~
耶瑟儿~ 2021-01-22 06:03
class A {
    int super_var = 1;
}

class B extends A {
    int sub_var = 2;
}

public class Demo{
    public static void main(String []args){        
        A a = new          


        
6条回答
  •  没有蜡笔的小新
    2021-01-22 06:28

    At first it does sound like it should work. (And in some languages it probably does.) But think about this example:

    public class Demo {
        public static void main(String []args){        
            A a = new B();
            print( a );
        }
    
        public static void print( A arg ) {
            System.out.print(arg.sub_var); //compile error
        }
    }
    

    This functionally does the same thing but the print is in another method. If your version worked, this one could be expected to work too.

    But what if someone then does this?

    Demo.print( new A() );
    

    This should fail because A doesn't have a sub_var. It would have to throw some kind of runtime error instead.

    So the design decision in Java was not to allow this and if you declare a local variable/field/method parameter as type A, then you can only access things that every object that is either A or a subclass is guaranteed to have.

    If you want to access more, you need to cast it to the subclass, which will throw an exception if you try it on an object that doesn't fit.

    A a = new A(); 
    System.out.print(((B)a).sub_var); //ClassCastException is thrown here 
    

提交回复
热议问题