Sub topic 9
Class-level state and behavior with static
A Java class is a definition for a kind of object. An object is one instance, or individual example, of that class. A field is a variable stored as part of a class or object. A method is a named block of code that performs a task.
Usually, each object has its own fields. A Ticket object, for example, might have its own ticket number. But sometimes information belongs to the class as a whole. A count of all tickets issued is an example.
The keyword static makes a field or method belong to the class rather than to one object. This chapter shows when to use it and how it differs from an instance member.
Instance members and static members
An instance member is a field or method used with a particular object. A static member is a field or method used with the class.
| Member | Belongs to | Example |
|---|---|---|
| Instance field | Each object has its own value | One ticket’s number |
| Instance method | Works with a particular object | Get that ticket’s number |
| Static field | The class has one shared value | Count of tickets issued |
| Static method | Can be called using the class name | Get the shared count |
Use the class name to access a static member, such as Ticket.getIssuedCount(). Use an object to access an instance member, such as first.getNumber().
Java also permits many static members to be accessed through an object. Avoid that style. Using the class name makes it clear that the member is shared.
Worked example: counting tickets
This program creates two tickets. Each ticket has its own number. The class also keeps a count shared by all tickets.
A constructor is a special part of a class that runs when an object is created. The Ticket constructor assigns a number to each new ticket.
Save this code in a file named Main.java:
class Ticket {
private static int issuedCount = 0;
private final int number;
Ticket() {
issuedCount++;
number = issuedCount;
}
int getNumber() {
return number;
}
static int getIssuedCount() {
return issuedCount;
}
static boolean comesBefore(Ticket first, Ticket second) {
return first.number < second.number;
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Before: " + Ticket.getIssuedCount());
Ticket first = new Ticket();
Ticket second = new Ticket();
System.out.println("First number: " + first.getNumber());
System.out.println("Second number: " + second.getNumber());
System.out.println("Issued: " + Ticket.getIssuedCount());
System.out.println("First comes before second: "
+ Ticket.comesBefore(first, second));
}
}Run these commands in the folder containing the file:
javac Main.java
java MainThe output is:
Before: 0
First number: 1
Second number: 2
Issued: 2
First comes before second: trueFollow the shared count
The field issuedCount is declared with static. It belongs to Ticket, not to an individual ticket. The word private means code outside Ticket cannot access the field directly. The class provides getIssuedCount() to read it.
Before the program creates any tickets, it calls Ticket.getIssuedCount(). This works because the method is static. No Ticket object is needed to call it.
Next, new Ticket() creates the first object. Its constructor adds one to the shared count using issuedCount++. It then assigns that count to the new ticket’s number field.
The second object goes through the same steps. It changes the same shared count from 1 to 2 and receives 2 as its number.
The count means “tickets issued during this run.” It does not mean “tickets currently in use.” The program never lowers it when a ticket is no longer needed.
Follow the individual numbers
The number field does not have static. It is an instance field, so each ticket has its own number.
The keyword final means the field can be assigned only once for each ticket. Here, the constructor assigns it. Later, first.getNumber() reads the first ticket’s number, while second.getNumber() reads the second ticket’s number.
The instance method getNumber() can use number directly. Java uses the number of the object on which the method was called.
What a static method can use
A static method has no particular object supplied by the method call. For example, Ticket.getIssuedCount() names the class, not a ticket.
A static method can directly use static fields and call other static methods in the same class. That is why getIssuedCount() can return issuedCount.
A static method cannot directly use an instance field as though it belonged to the class. If getIssuedCount() tried to return number without naming a ticket, Java would report an error: it would not know which ticket’s number to use.
A static method can still work with objects passed to it. The comesBefore method takes two parameters. A parameter is a named input to a method. Here, first and second each refer to a ticket.
Inside comesBefore, first.number means the number of the first ticket, and second.number means the number of the second. The method returns a boolean, a value that is either true or false.
The fields are private, but comesBefore can read them because the method is inside the Ticket class.
The keyword this means the current object in an instance method or constructor. A static method cannot use this because the call does not supply a current object.
Static constants
A constant is a value meant to stay fixed. Java often declares a class-level constant with both static and final.
The following complete program uses a constant and a static method. Save it as Conversion.java:
public class Conversion {
static final int SECONDS_PER_MINUTE = 60;
static int toSeconds(int minutes) {
return minutes * SECONDS_PER_MINUTE;
}
public static void main(String[] args) {
System.out.println(Conversion.toSeconds(3));
}
}Compile and run it with:
javac Conversion.java
java ConversionIt prints 180.
SECONDS_PER_MINUTE is shared because it is static. It cannot be reassigned because it is final. Java programmers commonly write constant names in uppercase with underscores between words.
The toSeconds method is static because its calculation needs an input value and a class constant, not a particular Conversion object.
Static fields and program runs
A static field keeps its shared value while its class is in use in an ordinary program run. Creating another object does not give the class a fresh copy of the field.
Java gives fields a starting value. For example, an int field starts at 0 if no value is supplied. The ticket example writes = 0 to make the starting count clear. Java initializes the class before its static members are first used; that does not happen again for every new ticket.
A static field is not automatically saved when the program ends. If you run the ticket program again, its count starts at 0 again.
Be careful when changing shared fields. A change made in one part of a program can affect what another part reads. Also, issuedCount++ is not a safe counting method when multiple tasks update the count at the same time. A real ticket service may need extra protection against that problem.
Why `main` is static
The main method is where Java starts running these programs. Java can call Main.main without first creating a Main object because the method is static.
In main, the program can still create objects and call their instance methods. It does this with first and second. The word void in the method declaration means the method does not return a value. String[] args holds any text arguments supplied when the program starts; these examples do not use them.
Choosing between instance and static
Use an instance field when each object needs its own value. Use an instance method when the operation is about one particular object.
Use a static field when the data is deliberately shared by the class. Use a static method when the operation does not need a current object, such as reading a shared count or converting minutes to seconds.
Before making a field static, ask whether changing it should affect every object that uses it. If the answer is no, an instance field is usually the better choice.
Practice
Exercise
If three Ticket objects are created in a fresh run of the ticket program, what do Ticket.getIssuedCount() and the third ticket’s getNumber() return?
Show answer
Both return 3. The count is shared, and the third ticket stores its own number, 3.
Exercise
Why can Ticket.comesBefore read first.number even though it is a static method?
Show answer
The first parameter supplies a particular Ticket object. The method is also inside Ticket, so it can read that class’s private fields.
Exercise
Should a field holding each student’s name be static or an instance field?
Show answer
It should be an instance field, because different student objects need to store different names.