Packages group related classes into namespaces; access modifiers decide who may see each class and member.
The four access levels
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
private | Yes | No | No | No |
| (default / package-private) | Yes | Yes | No | No |
protected | Yes | Yes | Yes (through inheritance) | No |
public | Yes | Yes | Yes | Yes |
Where each modifier is allowed
Top-level classes: only
publicor default. A source file may contain at most onepublictop-level class, and the file must be named after it.Members (fields, methods, constructors, nested types): all four.
Local variables: no access modifiers at all (only
final).Interface members:
publicby default; methods may also beprivate(Java 9+).
private is per class, not per object
public class Main {
public static void main(String[] args) {
Money a = new Money(500);
Money b = new Money(300);
System.out.println(a.isMoreThan(b));
// System.out.println(a.cents); // error: cents has private access in Money
}
}
class Money {
private final long cents;
Money(long cents) { this.cents = cents; }
boolean isMoreThan(Money other) {
return this.cents > other.cents; // OK: other object, same class
}
}truePackages
src/com/shop/billing/Invoice.java # package com.shop.billing;
src/com/shop/app/Main.java # package com.shop.app; import com.shop.billing.Invoice;
$ javac -d out $(find src -name '*.java')
$ java -cp out com.shop.app.MainNaming: reversed domain, all lowercase —
com.google.common.collect.java.langis imported automatically (String,Math,Integer,System…).Sub-packages are not related for access:
com.shopcannot see package-private members ofcom.shop.billing.Classes without a
packageline are in the unnamed package — fine for scripts, never for real projects.
Imports
import java.util.*; // on-demand: every public type in java.util
import java.time.LocalDate; // single-type import (preferred)
import static java.lang.Math.max; // static import of one member
import static java.lang.Math.PI;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(3, 9, 4));
System.out.println(max(nums.get(0), nums.get(1)));
System.out.printf("%.2f%n", PI);
System.out.println(LocalDate.of(2024, 2, 29).plusDays(1));
java.util.Date legacy = null; // fully qualified name, no import needed
System.out.println(legacy);
}
}9
3.14
2024-03-01
nullprotected in practice
protected members are visible to the whole package plus subclasses elsewhere — but a subclass in another package can only use them through its own type (this or a subclass reference), not through an arbitrary parent-class object.
Can a top-level class be private or protected?
What is the default access level?
Can an overriding method reduce visibility?