Understanding java's protected modifier

后端 未结 6 2255
感情败类
感情败类 2020-11-22 06:45

I have a class called A in package1 and another class called C in package2. Class C extends class A.

A has an instance variable which is declared like this:

<
6条回答
  •  时光取名叫无心
    2020-11-22 07:21

     public void go(){
            //remember the import statement
            A a = new A();
            System.out.println(a.publicInt);
            System.out.println(a.protectedInt);
    
        }
    

    When you are doing A a = new A(); and a.protectedInt you trying to access protected member of A which is illegal according to java standards

    Instead you can do this.protectedInt directly.

提交回复
热议问题