Access Modifiers
TL;DR
Access modifiers determine the visibility/accessibility of classes, methods, and variables.
public: Accessible from anywhere.protected: Accessible within the same package, and by subclasses in other packages.default(no keyword): Accessible only within the same package.private: Accessible only within the exact same class.
Concept
Modifiers are the core of Encapsulation. They allow you to define exactly who is allowed to see or modify your data.
| Modifier | Same Class | Same Package | Subclass (Diff Pkg) | Global (Anywhere) |
|---|---|---|---|---|
public | ✅ | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ✅ | ❌ |
default | ✅ | ✅ | ❌ | ❌ |
private | ✅ | ❌ | ❌ | ❌ |
Examples
// file: packageA/Person.java
package packageA;
public class Person {
public String name; // Anyone can read this
protected int age; // Package-private + child classes
String ssn; // Package-private (default)
private double salary; // Only Person methods can read this
public double getSalary() {
return salary; // Class itself can access private fields
}
}
// file: packageB/Employee.java
package packageB;
import packageA.Person;
public class Employee extends Person {
public void printInfo() {
System.out.println(name); // Allowed (public)
System.out.println(age); // Allowed (protected allows subclasses in diff packages)
// System.out.println(ssn); // ERROR: default is restricted to packageA
// System.out.println(salary); // ERROR: private is restricted to Person class
}
}
Interview Questions
Q: Can a top-level Class be private or protected?
A: No. A top-level class can only be public or default (package-private). If a top-level class were private, it would be completely invisible to everything, making it useless. However, Inner classes (classes defined inside other classes) can be private or protected.
Q: What is the default access modifier if you don’t specify one?
A: It is “package-private” (often just called “default”). It means the member is accessible to any other class in the exact same package, but completely hidden from classes outside that package (even subclasses).