why can not access child fields using parent reference

后端 未结 6 1841
耶瑟儿~
耶瑟儿~ 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:12

    you create an object of type B and assign it to a variable of type A. The type A does not declare sub_var. This field is declared only in type B. the compiler only sees what is declared in type A, although the variable is instantiated to an object of type B.

    If you want to access sub_var you would have to cast a to B.

    System.out.println( ((B)a).sub_var);

提交回复
热议问题