Java — Access Modifiers — Public, Private, Protected & Default
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.
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.
- 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.
- 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.
- 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.
- Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
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.
Controlling Access to Members of a Class
Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There…