Static fields and methods
Each object has its own copy of an ordinary field. But sometimes data belongs to the whole class at once: a counter of created objects, for example, or a fixed value. That is what the static keyword is for.
A static field
A field marked static exists in a single copy for the whole class. All objects see and change the same value:
class User {
static int count = 0;
String name;
User(String name) {
this.name = name;
count++;
}
}
void main() {
new User("Anna");
new User("Oleg");
IO.println(User.count);
}Output:
2A static field is accessed through the class name: User.count. No object is needed for that.
A static method
A static method also belongs to the class, not to an object. It is called through the class name. Helper methods that need no data of a particular object are built this way:
class Prices {
static double withTax(double price) {
return price * 1.2;
}
}
void main() {
IO.println(Prices.withTax(50));
}Output:
60.0You have already used such methods: Math.max(), Integer.parseInt() and String.valueOf() are static.
Constants
The combination static final gives a constant — one value per class that cannot be changed. By convention constant names are written in capital letters with underscores:
class Shop {
static final int MAX_ITEMS = 10;
static final String CURRENCY = "€";
}
void main() {
IO.println("No more than " + Shop.MAX_ITEMS + " items");
IO.println("Currency: " + Shop.CURRENCY);
}Output:
No more than 10 items
Currency: €Static and ordinary together
An ordinary method can use static fields, because the class always has them. Here every ticket gets a number from a shared counter:
class Ticket {
static int nextNumber = 1;
int number;
Ticket() {
number = nextNumber;
nextNumber++;
}
}
void main() {
Ticket a = new Ticket();
Ticket b = new Ticket();
IO.println(a.number + " and " + b.number);
}Output:
1 and 2When to use static
Make a field or a method static when it does not depend on a particular object: constants, counters, helper calculations. Data that each object has its own copy of must stay in ordinary fields. Too much static turns classes into a bag of global variables, and the program becomes hard to change.
Common mistake
A static method is called without an object, so it has no this and ordinary fields are not available in it. Accessing them does not compile:
class User {
String name;
static void show() {
IO.println(name);
}
}
void main() {
User.show();
}Output:
Main.java:5: error: non-static variable name cannot be referenced from a static context
IO.println(name);
^Either make the method an ordinary one and call it on an object, or pass the value it needs as a parameter.