Access modifiers in Java are keywords used to control the visibility and accessibility of classes, methods, variables, and constructors. They help implement encapsulation by restricting access to program components based on the required level of security and accessibility.
Key Points: • Java provides four access modifiers: public, protected, default (package-private), and private. • Access modifiers help protect data and control how different parts of an application interact. • They are an important part of encapsulation and object-oriented design. • The choice of access modifier depends on how widely a member should be accessible. • Proper use of access modifiers improves security, maintainability, and code organization.
Types of Access Modifiers:
1. public • Accessible from anywhere in the application. • Highest visibility level.
2. protected • Accessible within the same package and by subclasses in other packages.
3. default (No Modifier) • Accessible only within the same package. • Also called package-private access.
4. private • Accessible only within the same class. • Provides the highest level of data hiding.
Example: In a banking application, an account balance should typically be private to prevent direct modification, while public methods can be provided to deposit or withdraw money safely.
Code Example:
public class BankAccount {
private double balance = 1000;
public double getBalance() {
return balance;
}
protected void displayAccountInfo() {
System.out.println("Account Information");
}
}Access Modifier Visibility:
• public → Everywhere • protected → Same package + Subclasses • default → Same package only • private → Same class only
Interview Tip: A concise interview answer is:
"Access modifiers in Java control the visibility of classes, methods, variables, and constructors. Java provides public, protected, default, and private access modifiers, which help enforce encapsulation, improve security, and manage access to application components."