Java Modifiers
Modifiers are keywords placed in front of classes, fields, methods and constructors to change their meaning. You have already met several: public, static, final. Java splits them into two groups:
- Access modifiers control who can use a member.
- Non-access modifiers change how it behaves.
Access modifiers
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
public |
✓ | ✓ | ✓ | ✓ |
protected |
✓ | ✓ | ✓ | |
| (none) — "package-private" | ✓ | ✓ | ||
private |
✓ |
Top-level classes can only be public or package-private. Fields, methods and constructors can use all four.
class Vault {
public String label = "Main vault";
String location = "Basement"; // package-private
private int code = 4271;
public boolean open(int attempt) {
return attempt == code; // private field used inside its own class
}
}
class Main {
public static void main(String[] args) {
Vault v = new Vault();
System.out.println(v.label);
System.out.println(v.location); // OK: same package
// System.out.println(v.code); // error: code has private access in Vault
System.out.println(v.open(1234));
System.out.println(v.open(4271));
}
}Main vault
Basement
false
true
Tip: Start with the most restrictive access that works — usually
privatefor fields — and only open things up when another class truly needs them.
Non-access modifiers
| Modifier | On a class | On a field | On a method |
|---|---|---|---|
final |
can't be subclassed | can't be reassigned | can't be overridden |
static |
(nested classes only) | one copy per class | callable without an object |
abstract |
can't be instantiated | – | has no body; subclass must implement |
synchronized |
– | – | only one thread at a time |
transient |
– | skipped by serialization | – |
volatile |
– | always read from main memory | – |
static and final together
class AppConfig {
static final String APP_NAME = "TaskTracker";
static final int MAX_USERS = 50;
static int activeUsers = 0;
static boolean login() {
if (activeUsers >= MAX_USERS) return false;
activeUsers++;
return true;
}
}
class Main {
public static void main(String[] args) {
AppConfig.login();
AppConfig.login();
System.out.println(AppConfig.APP_NAME + ": " + AppConfig.activeUsers + "/" + AppConfig.MAX_USERS);
}
}TaskTracker: 2/50
final classes and methods
A final class can't be extended. String and Integer are final, so nobody can create a sneaky subclass that changes how they behave. A final method can be inherited but not overridden:
final class Money {
private final long cents;
Money(long cents) {
this.cents = cents;
}
final String format() {
return String.format("%d.%02d", cents / 100, cents % 100);
}
}
// class FakeMoney extends Money {} // error: cannot inherit from final Money
class Main {
public static void main(String[] args) {
Money price = new Money(1999);
System.out.println(price.format());
}
}19.99
abstract (preview)
An abstract class is a partial blueprint: it can't be instantiated, and its abstract methods have no body. Subclasses fill in the missing pieces:
abstract class Shape {
abstract double area();
void print() {
System.out.printf("%s with area %.2f%n", getClass().getSimpleName(), area());
}
}
class Square extends Shape {
double side = 3;
double area() {
return side * side;
}
}
class Main {
public static void main(String[] args) {
// Shape s = new Shape(); // error: Shape is abstract; cannot be instantiated
new Square().print();
}
}Square with area 9.00
You'll study abstract properly in the Abstraction chapter.
Order of modifiers
Java accepts modifiers in any order, but the conventional order is: access modifier first, then static, final, abstract and so on — for example public static final int MAX = 10;.
Test yourself
Which access modifier makes a member visible only inside its own class?
- public
- protected
- private
- No modifier
What does it mean when a field has no access modifier?
- It is public
- It is private
- It is visible within the same package
- It is invalid
What does final mean on a class?
- Its fields are constant
- It cannot be subclassed
- It cannot be instantiated
- All its methods are static