问题
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++.
回答1:
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
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/12861814/accessing-package-private-fields-in-java