In this article we learn the what is access modifiers in java and types of access modifiers.
What is Access Modifiers in Java?
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
Types of Access Modifiers in Java
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
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.
Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
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.
We cannot mark a class with a private access modifiers in Java
Declaring a class with the private access modifier would mean that no other classes can access it, which means we cannot really use the class at all. Using private with the main class or top-level class is useless because none of the members can have access to it.
Therefore, Java does not allow private access modifier for the classes. The Java compiler gives an error when we try to declare our main class as private.