Packages: Introduction to Access Modifiers

Access modifiers are one of the most confusing subjects that you will encounter when learning Java. Even seasoned veterans sometimes have difficulty remembering all the rules and how they apply in certain situations. When you throw inheritance into the equation, the topic becomes mind-boggling. I really struggled with the timing of when I should introduce the concept of access modifiers into my tutorial series. There are things such as static nested classes and inner classes that are considered members of a traditional (outer) class. I haven't even talked what an interface is or mentioned an enum yet. There is so much more to this language that access modifiers pertain to. For the context of this tutorial, the access modifiers will apply to classes, constructors, methods, and variables. With that being said, the four type of access are: public, default aka package-private, protected, and private.

Public Access Modifier

The public access modifier allows full access to all members of the same package and full access to members of other packages – basically everything.

Default Access (aka Package-Private) No-Modifier

When no modifier exists in a declaration statement, then the default (aka package-private) access is applied. Default access allows full access to only members of the same package.

Protected Access Modifier

Protected access allows full access to all members of the same package – exactly like default access. In addition, access is granted to subclasses of another package through inheritance only.

Private Access Modifier

The private access modifier only allows access to code inside of the current class. Packages are irrelevant when it comes to this access modifier.

Other Noteworthy Stuff

Standard classes (outer) can only have either public or default access, they cannot be marked protected or private. There is a common misconception that the access level of a class (outer) somehow controls the access level of its members. For example, a default access level class can have a public method; a public subclass will inherit that public method from within the same package. A class outside of the package can access the method through inheritance by extending the public subclass or by simply creating an instance of the public subclass.

Following this tutorial, I will make several more tutorials that discuss how access modifiers are used – or not used – in certain situations. I will only discuss access modifiers and how they pertain to concepts that I have introduced in my tutorial series thus far. In future tutorials, I will discuss how access modifiers are relevant to new concepts at the appropriate time.

Final thoughts

Because this tutorial is meant to be just a general overview, I did not make any code examples.