Java Access Modifiers
In Java, the access specifiers (also known as access modifiers) used to restrict the scope or accessibility of a class, constructor, variable, method or data member of class and interface. There are four access specifiers, and their list is below.
- default (or) no modifier
- public
- protected
- private
In java, we can not employ all access specifiers on everything. The following table describes where we can apply the access specifiers.
Let's look at the following example java code, which generates an error because a class does not allow private access specifier unless it is an inner class.
private class Sample{
...
}
In java, the accessibility of the members of a class or interface depends on its access specifiers. The following table provides information about the visibility of both data members and methods.
🔔 The public members can be accessed everywhere.
🔔 The private members can be accessed only inside the same class.
🔔 The protected members are accessible to every child class (same package or other packages).
🔔 The default members are accessible within the same package but not outside the package.
Let's look at the following example java code.
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass{
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.showData();
obj.accessData();
}
}
When we run this code, it produce the following output.