Java Tutorial – 16 – Access Levels

Java Tutorial – 16 – Access Levels

There are four access levels available in
Java. These are public, protected, private, and package-private. To show their differences
let’s create one field for each access level. First thing to note here is that package-private
cannot be explicitly declared using a keyword. Instead, it’s the default access level for
every member in Java. The most restrictive access level is private.
Members with this level can only be used inside of the defining class. Next, we have the package-private members
which can be accessed anywhere within the current package, but not from another package.
To demonstrate this we’ll go ahead and create another package along with a new source file.
If we try to access the fields from here we can see that the package-private field it
is no longer accessible and neither is the protected field. The only difference between
them is that protected members are also accessible to subclasses so if we extend MyApp here the
protected field will be inherited and become visible to this class. Note that the meaning
of protected in Java is different from other languages such as C++ and C#, where protected
members are only accessible from derived classes and the containing class. Finally, there’s the public modifier which
gives unrestricted access from anywhere we can reach the member. An example of this is
the MyApp class, which could be reached from the other package because it was marked as
public. Without the public modifier the class will default to package-private, and these
two are the only access levels allowed for top-level members. If the class was defined
on the class level instead it could then have either one of the 4 access levels. As a guideline when choosing an access level
it’s generally best to use the most restrictive level we can. This is because the more places
a member can be accessed the more places it can be accessed incorrectly, which makes the
code harder to debug.

2 thoughts on “Java Tutorial – 16 – Access Levels”

  1. ProgrammingVideos

    @InternetOblivion The disadvantage of using only public members is that it makes the code harder to debug, because the more places a member can be accessed the more places it can be accessed incorrectly. You typically want to use the most restrictive level you can for any member, at least in large commercial projects. For a small personal project you can of course simplify things by using only public members.

Leave a Reply

Your email address will not be published. Required fields are marked *