7

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++.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281

3 Answers3

28

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
NominSim
  • 8,447
  • 3
  • 28
  • 38
  • What constitutes a package in this context? All classes in namespace `java.io`? Or all classes in `java.io` in the same compilation unit? – Seva Alekseyev Oct 12 '12 at 15:16
  • The "namespace" `java.io` constitutes a package, so the breadth of `java.io` would have "package-level" access. – NominSim Oct 12 '12 at 15:21
  • So `I`, the API consumer, can poke around that field if I declare a class in `java.io`? Sounds like a pretty wild breach of encapsulation to me. – Seva Alekseyev Oct 12 '12 at 15:29
  • [@Seva Alekseyev](http://stackoverflow.com/users/219159/seva-alekseyev): yes you can. – Alex Cohn Oct 13 '12 at 14:52
  • The Android build system will yell and scream and error out, though, if you try declaring anything in `java.*`. – Seva Alekseyev Oct 14 '12 at 17:59
1

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
Mukul Goel
  • 8,387
  • 6
  • 37
  • 77
0

Package private field (and anything else) are just that: private within their package. This means that no other class can access the field (or other entity) outside of the scope of the package. For more specific detail, refer here.

ahodder
  • 11,353
  • 14
  • 71
  • 114