Access modifier
- Eclipse: Oxygen
- Java: 1.8
Access modifiers in Java help to restrict the scope of a class, constructor, variable, method, and data member.
There are four types of access modifiers:
- Private
- Public
- Protected
- Default – No keyword is required
The private access modifier is specified using the private keyword. It is accessible only within the class.
In private access modifier, methods or data members declared as private are accessible only within the class in which they are declared. Any other class in the same package will not be able to access these members. Classes or the top-level interface cannot be declared private because of private means “only visible within the attached class”.
In this example, we will create two packages org.studyeasy.parent and org.studyeasy.child. Class A in org.studyeasy.parent is made public, to access it in org.studyeasy.child. The variable display in class A is private and class B is inherited from class A and this private variable is then accessed by creating an object of class A.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package org.studyeasy.parent; //class A public class A { private int x = 10; public void demo(){ System.out.println("Value of x is "+x); } } package org.studyeasy; import org.studyeasy.parent.A; public class App { public static void main(String[] args) { new A().demo(); } } |
Output
Value of x is 10
The public variable is visible everywhere in contrast to the private variable which is local variable to a class and protected variable which is also not visible in the different classes until It has the same package.
The public access modifier is specified by the keyword public. You can access classes, methods or data members that are declared public from anywhere in the program. There are no restrictions on the scope of public data members.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.studyeasy.parent; //class A public class A { public int x = 10; public void demo(){ System.out.println("Value of x is "+x); } } package org.studyeasy; import org.studyeasy.parent.A; public class App { public static void main(String[] args) { new A().demo(); int test = new A().x; System.out.println(test); } } |
Output
Value of x is 10
10
Default access modifier:
In general default access modifier is accessible only within the package. If you do not use any modifier, it will be treated as default.
Protected access modifier:
The protected access modifier is accessible within the package and outside the package but only through inheritance. It can be applied to the data member, the method, and the constructor. It cannot be applied in the class.
Let’s understand the access modifiers by the following table.
Contributed by: Poonam Tomar