Sarpe
Sarpe

Reputation: 5806

Java package-private visibility members with /*package*/ suffix

Even if this is something I don't find often, what's the reason of the comment /* package*/ before the members?

 /* package */ final void attach(Context context) {
    attachBaseContext(context);
    mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}

Here is an example from AOSP line 180: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/app/Application.java

Upvotes: 3

Views: 1045

Answers (2)

Nameless Voice
Nameless Voice

Reputation: 461

By default, members in Java use package-level access - they can be accessed by other classes in the same package, but not by classes in other packages.

Actually using this functionality is fairly rare, since you normally want all of your variables to be private (or protected), and your methods to either be private (for self-use), protected, or public.

There is no explicit "package" modifier, so there's no easy way to know at a glance if the modifier is missing because the author forgot to include the correct one, or because they intentionally wanted the member to have package-level access.

That's why, in the somewhat rare cases when you want to use package, it's good practice to put a /* package */ comment in front of the method declaration, to clearly state that you are intentionally using this access level, rather than accidentally forgetting to specify one.

The comment itself doesn't actually do anything as far as the compiler is concerned - it just makes the code easier to understand.

Upvotes: 4

nanofarad
nanofarad

Reputation: 41281

As a comment, it has absolutely no effect on the compiler. It can be used, however, by humans to make it clear that a member (method or field) or class is package-private.

Upvotes: 4

Related Questions