What are Access Modifiers?
Access modifiers are keywords in Java that define the accessibility of classes, methods, constructors and variables.
They help us control where a particular member can be accessed.
Types of Access Modifiers
Java provides four access modifiers:
- public
- private
- protected
- default
1) Public
The public modifier allows a member to be accessed from anywhere, including other packages.
public class Student { public String name = "John"; public void display() { System.out.println(name); } } Here, the name variable and display() method can be accessed from anywhere.
2) Private
The private modifier allows a member to be accessed only within the same class.
public class Student { private int age = 22; private void display() { System.out.println(age); } } Here, the age variable and display() method cannot be accessed directly outside the Student class.
3) Protected
The protected modifier allows a member to be accessed:
- Within the same class.
- Within the same package.
- In subclasses belonging to other packages, subject to Java's inheritance access rules.
class Student { protected String name = "John"; } class Details extends Student { void display() { System.out.println(name); } } Here, the Details class can access the protected name variable through inheritance.
4) Default
When we don't specify any access modifier, Java uses the default access level, also called package-private.
It allows members to be accessed only within the same package.
class Student { String name = "John"; void display() { System.out.println(name); } } Here, both name and display() can be accessed by classes within the same package.
Access Modifier Comparison
| Modifier | Same Class | Same Package | Subclass (Different Package) | Other Packages |
|---|---|---|---|---|
| public | Yes | Yes | Yes | Yes |
| protected | Yes | Yes | Yes* | No |
| default | Yes | Yes | No | No |
| private | Yes | No | No | No |
*Protected access in another package is available through inheritance, with additional access restrictions.
Important Points
- Java has four access levels: public, private, protected and default.
- Private members can only be accessed within their own class.
- Default access is limited to the same package.
- Protected access supports inheritance across packages.
- Public members can be accessed from anywhere.
- Top-level classes can only use
publicor default access modifiers.
That's it! Access modifiers help us control the visibility of members and are an important part of encapsulation in Java.