Java Distinguish This Object from Class State
this identifies the current instance. static members belong to the class, so they are shared rather than copied into every object’s individual state.
Understand the idea
An instance method can use this to refer to fields or pass the current object to another operation. A static method has no current instance, so it cannot access an instance field without an explicit object reference. Static final constants can express stable shared values. Mutable static fields can accidentally turn an independent domain object into a source of application-wide hidden state.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
static class Session {
static final int CAPACITY = 10;
private final int booked;
Session(int booked) { this.booked = booked; }
int remaining() { return CAPACITY - this.booked; }
}
public static void main(String[] args) {
Session a = new Session(4);
Session b = new Session(7);
System.out.println(a.remaining());
System.out.println(b.remaining());
}
}
Expected output
6
3Both instances use the same fixed capacity but store different booked values. The result depends on the receiver’s field. A reservation counter would not belong in a static field merely because several methods need to read it; that would make unrelated instances share a single count.
Check the official Java documentation for detailed contracts and supported options.