Package-Private Members: Default Package Visibility
What you'll learn: How omitting an access modifier creates package-private visibility, allowing any class in the same package to access the member.
The Default Access Level
When you declare a class member (field or method) without any access modifier, Java assigns it package-private (also called default or package-level) access. 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 a workspace in a large office building. Package-private members are like documents left on a shared desk in your team's room—everyone on your team (same package) can see and use them, but people from other departments (other packages) cannot access them.
Syntax: Omission Is the Modifier
package com.example.billing;
class Invoice {
double amount; // package-private field (no modifier)
void calculate() { // package-private method (no modifier)
// implementation
}
}
Any other class in com.example.billing can access amount and calculate(). Classes in com.example.shipping cannot.
When to Use Package-Private
Package-private access is useful for members that should be shared among related classes in the same package but hidden from the outside world. It's more permissive than private (class-only) but more restrictive than public (everywhere).
package com.example.billing;
class TaxCalculator {
void processInvoice(Invoice invoice) {
invoice.amount = 100.0; // OK: same package
invoice.calculate(); // OK: same package
}
}
Key Takeaway: Omitting an access modifier creates package-private visibility, granting access to all classes in the same package while maintaining encapsulation boundaries across packages.