In Java, we have to deal with classes, methods, variables, etc. Let’s suppose we have a class and we need to use variables or methods in different classes/packages. OR we want to specify that a variable or method will be accessed within a defined area. To manage the accessibility of any variables, methods, or classes/packages we use Access Modifiers. In one word, Access Modifiers are responsible for managing the scope of variables, methods, etc.
In the above figure, we can see that each variable has its own scope of access within or outside the class.
Access Modifier Types:
There are mainly 4 types of access modifiers available in java. These are the kind of keyword that is used to define the scope or accessibility within or outside.
Default Access Modifier:
The Scope of the default modifier always deals inside the package.
If we don’t specify any scope for variables, methods, or classes then it automatically considers it a Default access modifier.
Public Access modifier:
Public access modifier can be used globally i.e. it can be accessible inside a package as well as another package also. We can specify the scope of any variable, method, or class/package using the PUBLIC keyword.
Private Access modifier:
The private access modifier provides accessibility inside the class we can not access outside the class. We can make any class private using the PRIVATE keyword. If we created a class constructor as private then we can not create an instance of that class as well.
Protected Access modifier:
Protected access modifiers allow the scope to be available within packages as well as sub-class of different packages. We can provide protected accessibility using the PROTECTED keyword.
Accessibility of access modifiers: