Java Modifiers
Modifiers control access and behavior of classes, methods, and fields. Access modifiers (public, private, protected, default/package-private) control visibility, while non-access modifiers (static, final, abstract) control other behavior.
Choosing appropriate modifiers is central to encapsulation and good API design.
public class C {
private int x;
static int count;
final int MAX = 10;
}Access modifiers
public is accessible everywhere, private only within the same class, protected within the package and subclasses, and default (no modifier) within the same package.
Non-access modifiers
static belongs to the class rather than an instance, final prevents changes (to variables, methods, or classes), and abstract marks something as incomplete, to be implemented by subclasses.
class Counter {
private static int count = 0;
Counter() { count++; }
static int getCount() { return count; }
}
public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println(Counter.getCount());
}
}2static count is shared across all Counter instances, tracking how many were created.
Key points
- private limits access to the same class only.
- public allows access from anywhere.
- static members belong to the class, not instances.
- final prevents reassignment or overriding.
