Java — Access Modifiers — Public, Private, Protected & Default

Kody Samaroo
2 min readJun 25, 2021

--

The access modifier is the keyword that precedes all other keywords when creating a class, method or even a variable. There are four keywords, public, private, protected & default, each with different levels of access. I believe it be best practice to start with the lower access levels and more up as needed. A variable that controls the width and height of a window can safely be reserved for private access.

“Final” is a powerful keyword as well, it makes those variables unchangeable after initializing. If you want a height, width, grid to be the same all the time binding those variables to final is a good idea.

So what’s going on?

In this example, we can see the use of both public and private. These two access modifiers in particular are very popular and you will see them everywhere. Understanding them will help immensely when you are first starting out. Oddly enough they are on opposite sides of the access level spectrum. While a public is the most open in access, private is the exact opposite and only exists in the class that it was initialized in or created. Here is a great chart defining the other access modifiers.

Reference: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
  1. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.
  2. Protected: The access level of a protected modifier is within the package and outside the package through the child class. If you do not make the child class, it cannot be accessed from outside the package.
  3. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
  4. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.

Conclusion

I included some sources that go in depth with each access modifier. Access modifiers are like keys and locks for your application. You can control the flow of data with them minimizing resource leaks and directly controlling classes.

While creating a hundred public sources and stuffing them into one class seems like an easy thing to do, best practice suggests otherwise. Following these principals not only will save you time in the long run but makes collaborating with other programmers better.

Reference

--

--