Class Variables and Constants
Variables that belong to a class rather than to each object: declaring them with static, sharing one copy among all objects, reaching public ones with the class name, and fixing values permanently with final.
Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. They are designated with the static keyword before the variable type. Class variables designated public are accessed outside the class by using the class name and the dot operator, since they are associated with a class, not objects of a class. When a variable is declared final, its value cannot be modified, which is how Java expresses named constants.
1Declaring Class Variables
A class variable is declared in the class body, outside every method and constructor, with the keyword static before its type: private static int totalLaps = 0;. It can be given a starting value right in the declaration, and that value is set once, when the class is first used, not each time an object is created.
Class variables hold information about the class as a whole: how many objects have been created, the next id to hand out, a setting that applies to every object, or a fixed constant. Like instance variables, they are usually private, with class methods or instance methods providing controlled access.
Because a class variable is not tied to any object, it exists even before the first object is created and keeps its value as objects come and go. A counter of created objects starts at 0 the moment the class is first used, increases with each constructor call, and keeps its total for the rest of the program.
| Instance variable | Class variable | |
|---|---|---|
| Declaration | private int laps; | private static int totalLaps; |
| Copies | One per object | One for the whole class |
| Accessed from outside (if public) | object.name | ClassName.name |
| Changed by one object | Only that object sees it | Every object sees it |
2One Copy Shared by All Objects
Class variables belong to the class, with all objects of a class sharing a single copy. Every object's methods read and write that same copy, so a change made through one object is immediately visible through all the others, and through class methods as well.
This is exactly right for shared information such as a running total, and exactly wrong for information that should differ between objects. If each player needs a separate score, score must be an instance variable; declaring it static makes every player share one score, and creating or updating any player changes it for all of them.
static.Counting Laps for Everyone
Each runner counts its own laps; a class variable counts everyone's. Predict the output.
public class Runner
{
private static int totalLaps = 0;
private int laps;
private String name;
public Runner(String n)
{
name = n;
laps = 0;
}
public void completeLap()
{
laps++;
totalLaps++;
}
public String report()
{
return name + " " + laps + " of " + totalLaps;
}
public static int getTotalLaps()
{
return totalLaps;
}
}
Ines 2 of 3
Tavi 1 of 3
3
- 1
lapsis per object: Ines has 2, Tavi has 1. - 2
totalLapsis shared: every call tocompleteLapincreases the one copy, so both reports show 3. - 3
Runner.getTotalLaps()reads the same shared value through a class method.
Changing One Setting for Every Object
All thermometers share one display setting. Predict the output.
public class Thermometer
{
private static boolean showFahrenheit = false;
private double celsius;
public Thermometer(double c)
{
celsius = c;
}
public static void useFahrenheit(boolean on)
{
showFahrenheit = on;
}
public String reading()
{
if (showFahrenheit)
{
return (celsius * 9 / 5 + 32) + " F";
}
return celsius + " C";
}
}
20.0 C, 5.0 C
68.0 F, 41.0 F
- 1Per-object data. Each thermometer keeps its own
celsiusreading. - 2Shared setting.
showFahrenheitis one class variable, changed by the class methoduseFahrenheit. - 3One change, every object. After the call, both thermometers report in Fahrenheit: 20 °C is 68.0 °F and 5 °C is 41.0 °F.
Per-Player Data Declared static
The programmer accidentally made score a class variable. Predict the output.
public class Player
{
private static int score;
private String name;
public Player(String n)
{
name = n;
score = 0;
}
public void addPoints(int p)
{
score = score + p;
}
public String show()
{
return name + ": " + score;
}
}
Oro: 5
Lumi: 5
- 1One shared score. Because
scoreis static, both players use the same variable. - 2Creating Lumi runs the constructor, which resets the shared score to 0, wiping out Oro's 30 points; Lumi's 5 points then apply to the shared copy.
- 3Fix. Remove
staticso each player has its own score.
If a value should be different for each object, such as a name, a score, or a position, it must not be static. A static field has only one copy, so every object would overwrite the others' values.
3Accessing Class Variables From Outside
Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class. Pool.LANE_COUNT needs no Pool object. Inside the class itself, the variable's name alone is enough.
The Java library uses the same pattern. Integer.MAX_VALUE and Integer.MIN_VALUE are public class variables of the Integer class, holding the largest and smallest int values. Public class variables are almost always also final, so that outside code can read them but never change them.
A class variable that is private cannot be reached by name from other classes at all. When outside code needs its value, the class provides a public class method, such as Runner.getTotalLaps(), which returns a copy. This keeps the shared value under the class's control while still making it available.
public are accessed outside the class by using the class name and the dot operator.| Library class constant | Value |
|---|---|
Integer.MAX_VALUE | 2147483647, the largest int |
Integer.MIN_VALUE | −2147483648, the smallest int |
Using a Constant From Another Class
Predict the output.
public class Pool
{
public static final int LANE_COUNT = 8;
public static final double LENGTH_M = 25.0;
public static double distance(int lengths)
{
return lengths * LENGTH_M;
}
}
8
400.0
16
true
- 1Class name, dot, variable.
Pool.LANE_COUNTreads the public class variable without anyPoolobject. - 2Inside the class,
distanceusesLENGTH_Mby name: 16 × 25.0 = 400.0. - 3Library constants such as
Integer.MAX_VALUEare public class variables reached the same way.
4final: Values That Cannot Change
When a variable is declared final, its value cannot be modified. A final variable is assigned exactly once, and any later assignment is a compile-time error: "cannot assign a value to final variable." This turns an intention ("this number should never change") into a rule the compiler enforces.
final applies to instance variables as well as class variables. A final instance variable, such as a race bib number, is assigned in the constructor and then stays fixed for that object's lifetime, while each object still has its own value.
The keyword can also be applied to local variables inside a method, as in final int limit = 10;. The rule is the same everywhere: once a final variable has its value, no statement may change it. Using final wherever a value is meant to stay fixed documents that intent and lets the compiler catch accidental changes.
final, its value cannot be modified. The compiler rejects any later assignment.Trying to Change a Constant
Explain the compile error.
public class Pool
{
public static final int LANE_COUNT = 8;
}
- 1
finalmeans fixed.LANE_COUNTwas given its value once, and no later assignment is allowed. - 2The compiler enforces it, so a constant can never be changed by mistake anywhere in the program.
final, its value cannot be modified.A Value Each Object Keeps Forever
Each runner gets a bib number that never changes. Predict the output.
public class Entrant
{
private static int nextBib = 100;
private final int bib;
private int laps;
public Entrant()
{
bib = nextBib;
nextBib++;
laps = 0;
}
public void completeLap()
{
laps++;
}
public String tag()
{
return "#" + bib + " laps " + laps;
}
}
#100 laps 0
#101 laps 1
- 1
nextBibis a class variable that hands out numbers: 100, then 101. - 2
bibis a final instance variable: each entrant has its own, assigned once in the constructor and never changed. - 3
lapschanges freely because it is not final.
final works for instance variables too: each object's value is set once and then fixed.A final instance variable must receive its value in its declaration or in every constructor; a mutator that assigns it does not compile. If a value must change later, it should not be final.
5static and final Together: Constants
A variable that is both static and final is a class constant: one shared copy whose value never changes, such as public static final int LANE_COUNT = 8;. By convention, constant names are written in capital letters with underscores between words, which makes them easy to recognize in code.
Named constants make programs clearer and safer than repeating literal numbers. lengths * LENGTH_M explains itself where lengths * 25.0 does not, and if the pool length ever changes, only one line must be edited. Because a constant is final, making it public does not weaken encapsulation: other classes can read it but cannot alter it.
static decides how many copies exist; final decides whether the value can change.| Declaration | Copies | Can change? | Typical use |
|---|---|---|---|
private int laps; | per object | yes | Ordinary attribute |
private static int totalLaps; | one shared | yes | Counter or shared setting |
private final int bib; | per object | no (after constructor) | Identifier fixed at creation |
public static final int LANE_COUNT = 8; | one shared | no | Named constant |
A Named Pass Mark
Predict the output.
public class Grader
{
public static final int PASS_MARK = 60;
public static final int TOP_MARK = 90;
public static String verdict(int score)
{
if (score >= TOP_MARK)
{
return "distinction";
}
if (score >= PASS_MARK)
{
return "pass";
}
return "retake";
}
}
distinction
pass
retake
Pass mark: 60
- 1Readable conditions.
score >= PASS_MARKsays what the 60 means. - 2Boundaries. 95 reaches the top mark; 60 is exactly the pass mark; 59 falls just short.
- 3Outside access. Other classes can read
Grader.PASS_MARK, but because it isfinal, none can change it.
Writing 25.0 in a dozen places makes code hard to read and easy to break: change one and miss another, and the program becomes inconsistent. Declare a named constant once and use its name everywhere.
6Choosing static and final Carefully
Two questions decide each attribute's declaration. First, should every object have its own value, or should one value be shared by the whole class? That decides static. Second, should the value ever change after it is set? That decides final. Answering both questions for every attribute in a class design prevents the most common mistakes.
Shared, changeable class variables should be used sparingly, because any part of the class can change them and every object is affected. Counters and id generators are good uses. Constants, by contrast, are safe to share widely and are encouraged wherever a fixed value has a meaning worth naming.
Java allows a.totalLaps inside the class, but it suggests that the value belongs to a, which it does not. Refer to class variables by name inside the class, and with the class name outside it: Runner.getTotalLaps() or Pool.LANE_COUNT.
Four Habits for Class Variables
1. static = One Copy
Shared by every object of the class.
2. Per-Object Data Is Not static
Names, scores, positions belong to each object.
3. ClassName.variable
Reach public class variables through the class.
4. final for Fixed Values
static final for named constants in CAPITALS.
Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type. Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class. When a variable is declared final, its value cannot be modified; a variable that is both static and final is a shared constant.