Why am I allowed "direct access" to an object's protected field, whose class is defined inside a different package?

StackOverflow https://stackoverflow.com/questions/23108727

  •  04-07-2023
  •  | 
  •  

Question

Main.java, main package:

package pkgs.main;
import pkgs.test.B;

// Just some method inside the "main class"
void method() {
    B b = new B();
    b.x ++;  //   <--- why is this allowed?
}

A.java, main package:

package pkgs.main;

public class A {
    protected int x;
}

B.java, test package:

package pkgs.test;
import pkgs.main.A;

public class B extends A {
}

Edit:

Another way of looking at this issue is as follows. I'll add two extra lines of code to the existing example code:

Main.java, main package:

// Just some method inside the "main class"
void method() {
    B b = new B();
    b.x ++;  //   <--- why is this allowed?

    b.y ++;  //   (Additional code) Compilation ERROR, which is correct.
}

B.java, test package:

public class B extends A {
    protected int y;  // (Additional code)  protected field;
                      // access to it is disallowed inside the 
                      // "main calling class" above.
}
Was it helpful?

Solution 3

“direct access” to an object's protected field is allowed in this particular example case, because the protected field declaration was made in a class that resides inside the same package as the "calling code". I guess Java doesn't look to see in which package the field is actually being used (ie inside a different package via inheritance). Java is only interested in the location where the field is originally declared.

OTHER TIPS

Since B extends A , protected fields allowed access to it's children also.

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Please prefer to read Controlling Access to Members of a Class

Modifier    Class   Package Subclass    World
---------------------------------------------

protected   Y      Y        **Y**           N

Maybe you misunderstood the concept of "protected".

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Source

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top