Date: 16-April-2025
Access Modifiers:
Accessibility is one of the major concerns in programming. Setting access to particular data in a program is a crucial aspect, especially when it comes to sensitive data. If it's not configured properly, the application may become unusable.
For example,
Let us consider a scenario where we are developing a project for government requirements. The government states that some of the information in this project is highly sensitive and must not be leaked. This is exactly where we need accessibility control over the data.
Is there any way to take control over accessibility?
Yes, there is a way to achieve this.
In Java, a concept called Access Modifiers is used for managing access-related functionalities.
Access modifiers in Java are used to control the access to the states (data members) and behaviors (methods) of a class.
But how?
By defining the elements with:
private
default
protected
public
The above four terms are known as access modifiers in Java.
Note: These are all keywords, and developers should not use them as reference names.
Let’s see the functions of each access modifier:
- private
The name itself explains the functionality—private. The private access modifier is used to limit the access of states and behaviors strictly within the class they belong to.
If I declare a state or behavior as private, I can access them only inside that class. If I try to access them from outside, Java will throw an error.
Where can we use the private modifier?
We can declare a state as private.
We can declare a behavior (method) as private.
We can declare a constructor as private.
Where can't we use the private modifier?
I. We cannot declare a top-level class as private. A class shouldn't be private.
Syntax:
private int a;
private void display() {
System.out.println("Private");
}
II. default
The default modifier limits the access of states and behaviors to within the same package.
We can access the members anywhere inside the same package, but not from outside the package.
Unlike private, we don't need to explicitly mention the default modifier. If we do not mention any access modifier in front of a state or behavior, it is considered to have default access.
Syntax:
int age;
void display() {
System.out.println("Default");
}
III. public
public is another modifier in Java. It doesn't restrict access to any data.
If I declare a statement as public, I can access it from anywhere throughout the program.
We will discuss the protected modifier in future blogs.