The access to classes, constructors, methods, and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes.
Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has a package or default accessibility when no accessibility modifier is specified.
Access Modifiers
- private
- protected
- public
public access modifier
public means every classes or every subclass or superclass can access fields. The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
private access modifier
The private access modifier is accessible only within class.
protected access modifier
The protected access modifier is accessible within package and outside the package but through inheritance only.The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
class BaseClass {
public int x = 10;
private int y = 10;
protected int z = 10;
int a = 10; // Implicit Default Access Modifier
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
private int getY() {
return y;
}
private void setY(int y) {
this.y = y;
}
protected int getZ() {
return z;
}
protected void setZ(int z) {
this.z = z;
}
int getA() {
return a;
}
void setA(int a) {
this.a = a;
}
}
public class Sample extends BaseClass {
public static void main(String args[]) {
BaseClass rr = new BaseClass();
rr.z = 0;
Sample subClassObj = new Sample();
// Access Modifiers - Public
System.out.println("Value of x is : " + subClassObj.x);
subClassObj.setX(20);
System.out.println("Value of x is : " + subClassObj.x);
// Access Modifiers - Public
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are private
// Access Modifiers - Protected
System.out.println("Value of z is : " + subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : " + subClassObj.z);
// Access Modifiers - Default
System.out.println("Value of x is : " + subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of x is : " + subClassObj.a);
}
}
Output-:
Value of x is : 10
Value of x is : 20
Value of z is : 10
Value of z is : 30
Value of x is : 10
Value of x is : 20
Access Modifier | within class | within package | subclass only | outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Leave Comment