Java Modifiers
Modifiers are keywords you place in front of classes, fields, and methods to control how they can be accessed and how they behave. Java splits them into two groups: access modifiers and non-access modifiers.
Access modifiers
Access modifiers decide who is allowed to see and use a member. Choosing the right one is how you protect the inner workings of a class while still exposing the parts other code genuinely needs.
Access modifiers in action
public class Account {
public String owner; // visible everywhere
private double balance; // hidden from outside code
public double getBalance() {
return balance; // the class itself can read its private field
}
}Non-access modifiers
Non-access modifiers do not change visibility. Instead, they change behavior, such as whether a value can be reassigned or whether a member belongs to the class as a whole rather than to a single object.
- final: the value or method cannot be changed or overridden.
- static: the member belongs to the class, not to any one object.
- abstract: used on classes and methods that must be completed by a subclass.
- default and synchronized: mainly used with interfaces and threads in more advanced code.
final and static
public class MathHelper {
static final double PI = 3.14159; // a shared, unchangeable constant
static int callCount = 0; // one counter shared by all objects
static double circleArea(double r) {
callCount++;
return PI * r * r;
}
public static void main(String[] args) {
System.out.println(MathHelper.circleArea(2)); // 12.56636
System.out.println(MathHelper.callCount); // 1
}
}Note: Because static members belong to the class, you reach them through the class name, like MathHelper.PI, without creating an object first.
Note: Once a variable is declared final and given a value, any attempt to reassign it causes a compile-time error. This is a helpful safety net for values that should never change.
Exercise: Java Modifiers
Which access modifier restricts a member to be visible only within its own class?