Accessing package-private fields in Java

南楼画角 提交于 2019-12-07 01:30:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!