Static Members and Enums
static members belong to the class, not to one object. An enum defines a fixed set of constants and can have fields and methods. They are ideal for things like days, levels or statuses.
Example
enum Level {
BEGINNER(1), INTERMEDIATE(2), ADVANCED(3);
final int rank;
Level(int rank) { this.rank = rank; }
}
class Counter {
static int total = 0;
Counter() { total++; }
}
public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println(Counter.total);
for (Level l : Level.values()) {
System.out.println(l + " " + l.rank);
}
}
}Result
2 BEGINNER 1 INTERMEDIATE 2 ADVANCED 3
Exercise
A field shared by the whole class is...
int total;Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.