Easy java core-java

What do the access modifiers and the static keyword mean?

The 30 second answer

There are four access levels: public is visible everywhere, protected is visible in the same package and in subclasses, package-private, with no keyword, is visible only in the same package, and private is visible only inside the class. Static means the member belongs to the class, not to an object, so there is one copy shared by all instances, and static methods can't use this or instance fields. I keep fields private and use the smallest access that works.

<!-- level: 1 --> <!-- must_know: true -->

ModifierClassPackageSubclassWorld
publicYesYesYesYes
protectedYesYesYesNo
none (package-private)YesYesNoNo
privateYesNoNoNo

The table is the one in the Java tutorial, which also advises using the most restrictive level that makes sense and avoiding public fields except for constants.

**static:**

  • A static field is a class variable: one copy for the class, shared by every instance.
  • A static method is called on the class (Math.max(a, b)) and can't use this or instance members directly.
  • A static nested class doesn't hold a reference to an outer instance.
  • static final fields are constants.
  • Interview trap: a mutable static collection lives as long as the class does, which is a classic memory leak in long-running services.
Sources (2)
  1. Java tutorial: Controlling access to members of a classdocs.oracle.com
  2. Java tutorial: Understanding class members (static)docs.oracle.com