Instance Variables and Class Variables
Instance Variables: State Each Object Keeps
Every object you create from a class needs somewhere to store its own data: a bank account its balance, a player their score, a thermostat its target temperature. In Java that data lives in instance variables. You meet them in your first class with fields and use them in every class after that, because methods read and update them to give each object its behaviour.
Declaring an instance variable
An instance variable is a variable declared inside a class but outside every method and constructor, without the keyword static. Each object created with new receives its own copy, and together those copies make up the object's state.
public class Thermostat {
private String room; // instance variable
private double target; // instance variable, degrees Celsius
public Thermostat(String room, double target) {
this.room = room;
this.target = target;
}
public void raise(double amount) {
target += amount;
}
public double getTarget() {
return target;
}
}Instance variables are also called fields. Declaring them private is standard practice; how access modifiers protect them is a separate topic. A field declared static is a single class-level variable shared by all objects, which belongs to static members rather than to this lesson.
One copy per object
The code below creates two thermostats and then changes one of them.
Thermostat a = new Thermostat("Kitchen", 21.0);
Thermostat b = new Thermostat("Office", 19.5);
a.raise(2.0);Each new allocates a separate object on the heap, with its own room and target. When a.raise(2.0) runs, the name target inside the method means the target of the object that a refers to, so changing one object's field never changes another object's copy.
Example: After the three lines above, a.getTarget() returns 23.0 while b.getTarget() still returns 19.5.
Lifetime, scope and default values
Instance variables differ from the other variables you write inside a class in where they live, how long they last and how they start.
Feature | Instance variable | Local variable | Parameter |
|---|---|---|---|
Where declared | Class body, outside methods | Inside a method or block | Method or constructor header |
Exists while | The object exists | Its block is running | Its call is running |
Visible in | Constructors and non-static methods of the class | From its declaration to the end of its block | The whole method or constructor body |
Starting value | 0, 0.0, false or null by type | None until assigned | The argument passed in |
Because Java fills every field with a default, a constructor that forgets a field leaves it at 0, 0.0, false or null instead of causing an error. Local variables get no default: a local variable must be assigned before it is read, or the code does not compile.
When a parameter hides a field
When a parameter or local variable has the same name as a field, the nearer declaration wins inside its scope. This is shadowing: in the constructor above, the plain name target means the parameter, so you write this.target to reach the field. The keyword this is a reference to the object whose constructor or method is running.
A local declaration shadows a field in the same way. Writing double target = 25.0; inside a method creates a new local variable; the assignment changes only that local, and the field is untouched once the method returns.
What to remember
- An instance variable is declared in the class body without static; each object stores its own copy.
- A method reads and updates the fields of the object it is called on.
- Fields start at default values (0, 0.0, false, null); local variables do not.
- A parameter or local with a field's name shadows it; use this.name to reach the field.
Example: Tracing two water tanks
A water utility simulation models storage tanks with the class below. Capacities and levels are in litres.
public class WaterTank {
private int capacity; // litres
private int level; // litres
public WaterTank(int capacity) {
this.capacity = capacity;
}
public void fill(int litres) {
level += litres;
if (level > capacity) {
level = capacity;
}
}
public int drain(int litres) {
int removed = Math.min(litres, level);
level -= removed;
return removed;
}
public int getLevel() {
return level;
}
}The program then runs these statements in order.
WaterTank north = new WaterTank(500);
WaterTank south = new WaterTank(300);
north.fill(350);
south.fill(200);
north.fill(220);
int moved = north.drain(180);
south.fill(moved);a) What is the value of level in each tank immediately after both constructor calls?
The constructor assigns only the field ________, so level is never set. Because level is an int instance variable, it keeps its default value of 0.
The two objects get separate copies of both fields: north has capacity 500 L and south has capacity 300 L. Each tank starts with a level of 0 litres.
b) Find the level of north after north.drain(180) runs.
Only calls on north change the fields of north, so you can skip the line south.fill(200) here.
- north.fill(350): level goes from 0 to ________ litres, which is within the capacity of 500 L.
- north.fill(220): level becomes 350 + 220 = ________ litres. That exceeds capacity, so the if statement sets level to ________ litres.
- north.drain(180): the local variable removed is Math.min(180, 500), which is ________ litres. Then level becomes 500 − 180 = 320 litres, and the method returns 180, which is stored in moved.
The level of north after the drain is 320 litres.
c) Find the final level of south.
south.fill(200) raised the level of south from 0 to ________ litres. None of the calls on north touched it, because south has its own copy of level.
south.fill(moved) passes 180 into the parameter litres, so level becomes 200 + 180 = ________ litres. That exceeds the capacity of south, which is 300 L, so the if statement caps level at capacity.
The final level of south is 300 litres.
d) Classify each of capacity, level, litres, removed and moved as an instance variable, a parameter or a local variable.
- capacity and level are instance variables: they are declared in the class body outside every method, without static, and each WaterTank object keeps its own copy for as long as it exists.
- litres is a parameter of both fill and drain; it receives the argument and exists only during that call.
- removed is a local variable of drain; it exists only while drain runs, which is why the method returns its value.
- moved is a local variable of the code that calls the methods; it is not part of any WaterTank object.
A bicycle-rental program represents each bicycle with a separate RentalBike object. Every bicycle uses one shared hourly rental rate, while each bicycle records its own distance travelled. A rate change must immediately apply to every existing bicycle and every bicycle added later.
Complete each statement with either instance variable or class variable.
The shared hourly rental rate should be stored in a .
Each bicycle's distance travelled should be stored in an .
A student is reviewing how variables behave in Java classes and writes the statements below. Which of these statements are true? Select every true statement.