ProLesson 4.4Beginner3 min readUpdated 30 October 2026
static members
Understand what belongs to the class instead of each object, when to use static fields and methods, and the rules static code must follow.
Normally every object has its own copy of each field. Sometimes a value belongs to the class as a whole: a counter of how many objects were created, a tax rate, or a helper method that needs no object. That's what static is for.
01Static fields: one copy, shared
StaticCounter.java
class Ticket {
static int issued = 0; // one copy for the whole class
final int number; // each ticket has its own
Ticket() {
issued++;
number = issued;
}
}
public class StaticCounter {
public static void main(String[] args) {
Ticket a = new Ticket();
Ticket b = new Ticket();
Ticket c = new Ticket();
System.out.println(a.number + ", " + b.number + ", " + c.number);
System.out.println("Issued: " + Ticket.issued); // access through the class name
}
}1, 2, 3 Issued: 3
Loading the rest of the lesson…