Understanding java's protected modifier

后端 未结 6 2166
感情败类
感情败类 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:25

    Within the same package where the protected member is declared, access is permitted:

    package package1;
    
    public class C extends A{
        public void go(){
            A a = new A();
            System.out.println(a.protectedInt);  // got printed 
            C c = new C();
            System.out.println(c.protectedInt);  // got printed as well
        }
    }
    

    Outside the package where the protected member is declared, access is permitted if and only if by code that is responsible for the implementation of that object. In this case, C is responsible for the implementation of that object, so it could access the protected.

    package package2;
    
    public class C extends A{
        public void go(){
            A a = new A();
            System.out.println(a.protectedInt);  // compiler complains  
            C c = new C();
            System.out.println(c.protectedInt);  // got printed
        }
    } 
    

提交回复
热议问题