OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 4 : Access Control for Class Members in Java
Unit - 2
Topic 4 : Access Control for Class Members in Java
In Java, encapsulation not only links data with the code that manipulates it, but it also controls how the data and methods are accessed from outside the class. This is achieved using access specifiers (also called access modifiers).
Java provides four levels of access control:
-
public
-
private
-
protected
-
default (no specifier)
1. public
-
A public member is accessible from anywhere in the program.
-
It can be accessed by classes in the same package as well as classes in different packages.
Example:
2. private
-
A private member can be accessed only within its own class.
-
It is not visible to other classes, even if they are in the same package.
-
This is the most restrictive access level.
Example:
3. protected
-
A protected member can be accessed:
-
Within the same class.
-
Within the same package.
-
By subclasses (even if they are in different packages).
-
Example:
4. Default (Package-Private)
-
If no access specifier is used, the member is accessible only within the same package.
-
This is called package-private access.
Example:
Access Control Table
Modifier | Same Class | Same Package | Subclass (diff package) | Other Packages |
---|---|---|---|---|
public | ✅ | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ✅ | ❌ |
default | ✅ | ✅ | ❌ | ❌ |
private | ✅ | ❌ | ❌ | ❌ |
Key Notes
-
private → Most restrictive, best for encapsulation.
-
public → Least restrictive, used for APIs and widely accessible methods.
-
protected → Useful in inheritance.
-
default → Good for package-level encapsulation.
Comments
Post a Comment