Access Modifiers
Access modifiers (Specifiers) in Java are keywords that control the visibility and accessibility of classes, methods, and variables. They ensure encapsulation, data hiding, and maintainability of code by regulating access to members.

Public
Description
public
access modifier allows unrestricted access to a class, method, or variable from any other class.
Example
public class PublicExample {
public int publicVariable = 10;
public void publicMethod() {
System.out.println("This is a public method.");
}
}
Private
Description
private
access modifier restricts access to members within the same class. They are not accessible from outside the class.
Example
public class PrivateExample {
private int privateVariable = 20;
private void privateMethod() {
System.out.println("This is a private method.");
}
}
Protected
Description
protected
access modifier allows access to members within the same package or subclasses, even if they are in different packages.
Example
public class ProtectedExample {
protected int protectedVariable = 30;
protected void protectedMethod() {
System.out.println("This is a protected method.");
}
}
Default (Package-private)
Description
Members with no access modifier (also known as package-private) are accessible only within the same package.
Example
class DefaultExample {
int defaultVariable = 40;
void defaultMethod() {
System.out.println("This is a default method.");
}
}
Brief Comparison Table
public
Global
Yes
Yes
Yes
Yes
private
Local
Yes
No
No
No
protected
Package and Subclass
Yes
Yes
Yes
No
default
Package
Yes
No
Yes
No
Summary
Public: Use when you want unrestricted access to members.
Private: Use for encapsulation and to restrict access to members.
Protected: Use when you want members accessible within subclasses or the same package.
Default (Package-private): Use for package-level encapsulation and restricted access.
Choose the appropriate access modifier based on the desired level of encapsulation and access control required for your classes, methods, and variables.
Last updated
Was this helpful?