Package-Private (Default) Access
You'll learn how omitting an access modifier creates package-private access, making members visible throughout the same package but hidden from other packages.
What Is Package-Private Access?
When you declare a class member (field, method, constructor, or even the class itself) without any access modifier, Java applies package-private access by default. This means the member is accessible to all classes within the same package, but invisible to classes in different packages.
Think of a package as an office floor in a building. Package-private is like leaving your door unlocked: anyone on your floor can walk in, but people from other floors can't access your office.
Syntax: Just Omit the Modifier
class Employee {
String department; // package-private field
int salary; // package-private field
void promote() { // package-private method
salary += 5000;
}
}
Notice there's no private, public, or protected keyword. That's intentional — the absence of a modifier means package-private.
Who Can Access Package-Private Members?
Any class in the same package can access these members directly:
// In the same package
class PayrollSystem {
void processPay(Employee emp) {
System.out.println(emp.department); // ✓ Allowed
emp.promote(); // ✓ Allowed
}
}
But classes in different packages cannot:
// In a different package
class ExternalAuditor {
void audit(Employee emp) {
System.out.println(emp.salary); // ✗ Compile error
}
}
Key Takeaway: Package-private (default) access is Java's middle ground — more open than private (same class only), but more restrictive than public (everyone). It's ideal for implementation details shared among related classes in the same package.