Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing package-private fields in Java

Poking around Android API sources. There's FileDescriptor with a data member descriptor with no access modifier:

int descriptor;

Then there's class FileOutputStream that constructs a new FileDescriptor and assigns to that field:

fd = new FileDescriptor();
fd.descriptor = fileSystem.open(...);

How is that compatible with the field access control model of Java? I thought package-private fields are not accessible from outside the declaring class, and there's no notion of friendship like in C++.

like image 896
Seva Alekseyev Avatar asked Oct 12 '12 14:10

Seva Alekseyev


2 Answers

Basically, package-private can be accessed at the class and package levels:

From the source:

Access Levels
Modifier    Class   Package  Subclass World
public         Y        Y       Y       Y
protected      Y        Y       Y       N
no modifier    Y        Y       N       N
private        Y        N       N       N
like image 62
NominSim Avatar answered Sep 28 '22 14:09

NominSim


a Declaration with no modifier, like

int descriptor;

Are package private, more commonly referred as DEFAULT are accessible within the package and not outside the package. Any class inside the same package can access these but these are not visible outside package.

For more details please refer here

Access Levels
Modifier        Class   Package     Subclass    World
public            Y         Y        Y            Y
protected         Y         Y          Y          N
no modifier       Y         Y          N          N
private           Y         N          N          N
like image 29
Mukul Goel Avatar answered Sep 28 '22 14:09

Mukul Goel