why can not access child fields using parent reference

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

    Is there a variable called sub_var in the parent class ? No. That is why you get the error -

    sub_var cannot be resolved or is not a field
    

    See this

    System.out.print(a.super_var); //okay
    System.out.print(a.sub_var); //compile error
    

提交回复
热议问题