why can not access child fields using parent reference

后端 未结 6 1865
耶瑟儿~
耶瑟儿~ 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 can not access B members with the reference of Parent object A.

    Instead change your println statement like below to access,

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

提交回复
热议问题