Access Modifier in Java
The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields.
If you are aware of C++ language, when we declare any member inside a class without public keyword then it is by default taken as private. But in Java, there are four different types of access modifiers, and if we do not specify access modifier for member or class it is considered as default modifier.
We can use modifiers with the class, but we can use only two access specifier (public or default) with the outer class. Whereas, for inner class we can use any of the four modifiers.
There are four types of access modifiers in Java:
- Private: Its access level is only within the class. It can’t be accessed from outside that class.
- Protected: Its access level is within the package and outside the package through child class.
- Public: Its access level is everywhere because it can be accessed within the class, outside the class, within the package, and outside the package. This is why the main() method has always been defined by the public modifier.
- Default: Its access level is only within the package because it cannot be accessed outside the package. If we do not specify and access modifier, it will be marked as default. It is more restrictive than protected.
Let's understand that where access modifier being used by a simple table:
Access Modifier | Same Class | Same package Subclass | Same Package Non-subclass | Different package Subclass | Different Package Non-subclass |
Private | Yes | No | No | No | No |
Default | Yes | Yes | Yes | No | No |
Protected | Yes | Yes | Yes | Yes | No |
Public | Yes | Yes | Yes | Yes | Yes |
Example to illustrate the working of access modifiers.
classprivateDemo { int add; // default access publicint sub; // public access privateintdiv; // private access // declaring method to access c voidsetdiv(inti) { // setting div's value div = i; } intgetdiv() { // getting div's value returndiv; } } classaccessDemo { publicstaticvoid main(String args[]) { privateDemoobj = newprivateDemo(); obj.add = 10; obj.sub = 20; // obj.c = 100; // It will give a compile time Error! because of access violation // We must access div through its methods obj.setdiv(100); // it sets the value of div System.out.println("add, sub, and div: " + obj.add + " " +obj.sub + " " + obj.getdiv()); } }
Output:
add, sub, and div: 10 20 100
As we can see, inside the privateDemo class, add uses default access, which is the same as specifying public. sub is explicitly declared as public. And member div is declared private i.e. it cannot be accessed by code outside of the class. So inside the accessDemo class, div can’t be used directly. We accessed it through a public method i.e. setdiv() and getdiv().