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

“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.

Reference

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store