Java ยท Chapter 24 of 42

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.

Syntax
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.

Example 1 (java)
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());
  }
}
Output
2

static 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.
๐Ÿ’ก Note: Prefer the most restrictive access modifier possible โ€” start with private and widen only when necessary.

๐Ÿ“ Quick Quiz

1. Which modifier restricts access to the same class only?

2. What does static mean for a field?

3. What does final prevent?