Writing Constructors: Initializing State
What an object's state is, how a constructor sets it, what happens in memory when a constructor runs, the default constructor and default values, and why mutable objects passed to a constructor should be copied.
An object's state refers to its attributes and their values at a given time, defined by the instance variables belonging to the object; this is a has-a relationship between an object and its instance variables. A constructor is used to set the initial state of an object, which should include initial values for all instance variables. When a constructor is called, memory is allocated for the object and the object reference is returned. If no constructor is written, Java provides a no-parameter default constructor that uses default values. When a mutable object is passed to a constructor, the instance variable should store a copy.
1Object State and the has-a Relationship
An object's state refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. A bike object has a number of gears, has a color, and has an odometer reading; this defines a has-a relationship between the object and its instance variables. As methods run, the values change, and the object's state changes with them.
Instance variables are declared in the class, outside any method or constructor, usually as private. Declaring them says what every object will have; it does not give them meaningful values. That is the constructor's job, and it is the first code that runs for every new object.
2Writing a Constructor
A constructor is used to set the initial state of an object, which should include initial values for all instance variables. Its header has the class name and no return type, and its body assigns each instance variable. Constructor parameters, if specified, provide data to initialize instance variables; values that are the same for every new object, such as an odometer starting at 0, are written directly.
When a constructor is called, memory is allocated for the object and the associated object reference is returned. The new object's instance variables briefly hold default values; the constructor body then replaces them with the intended starting values; finally the reference to the finished object is returned to the code that used new.
| Constructor fact | Detail |
|---|---|
| Purpose | Set the initial state of an object, including initial values for all instance variables |
| What a call does | Allocates memory for the object and returns the associated object reference |
| Parameters | If specified, provide data to initialize instance variables |
| No constructor written | Java provides a no-parameter default constructor that uses default values |
Initializing Every Instance Variable
Write a constructor for Bike that takes the number of gears and a color, and starts the odometer at 0.
public class Bike
{
private int gears;
private String color;
private double odometerKm;
public Bike(int g, String c)
{
gears = g;
color = c;
odometerKm = 0.0;
}
public void ride(double km)
{
odometerKm = odometerKm + km;
}
public String describe()
{
return gears + "-speed " + color + ", " + odometerKm + " km";
}
}
21-speed teal, 0.0 km
21-speed teal, 12.5 km
- 1Parameters supply data.
gandcprovide the values forgearsandcolor. - 2Fixed starting value. Every new bike starts with
odometerKm0.0, so that value is written in the constructor, not passed in. - 3Every instance variable is set. The object starts in a complete, meaningful state.
Writing int gears = g; inside the constructor creates a new local variable named gears that disappears when the constructor ends; the instance variable stays at its default. Assign the instance variable with gears = g;, with no type in front.
3Several Constructors
A class can provide more than one constructor, each with a different parameter list. A no-parameter constructor might choose typical starting values, while another lets the caller specify them. Each constructor must leave the object in a complete, valid state, so every one of them should initialize every instance variable.
When several constructors share most of their work, keep their behavior consistent: the same attribute should never be left uninitialized by one constructor and set by another. Readers of the class should be able to look at any constructor and see the full starting state of the object.
A constructor is also the natural place to enforce rules about valid starting values. If a thermostat must stay between 10 and 30 degrees, the constructor can check its parameter and adjust or reject values outside that range, so no thermostat ever begins in an impossible state. Methods that later change the state can apply the same rule, ideally through a shared private helper.
A Default Bike and a Custom Bike
Classes often offer several constructors. Predict the output.
public class Bike
{
private int gears;
private String color;
public Bike()
{
gears = 1;
color = "black";
}
public Bike(int g, String c)
{
gears = g;
color = c;
}
public String describe()
{
return gears + "-speed " + color;
}
}
1-speed black
7-speed orange
- 1
new Bike()runs the no-parameter constructor, which chooses sensible starting values itself. - 2
new Bike(7, "orange")runs the two-parameter constructor. - 3Both constructors set every instance variable, so either way the object is complete.
Refusing an Invalid Starting Value
A thermostat accepts a starting temperature but must stay between 10 and 30 degrees. The constructor enforces the rule. Predict the output.
public class Thermostat
{
private int target;
public Thermostat(int t)
{
if (t < 10)
{
target = 10;
}
else if (t > 30)
{
target = 30;
}
else
{
target = t;
}
}
public int getTarget()
{
return target;
}
}
21
10
30
- 1Valid input is stored as given: 21.
- 2Out-of-range input is replaced by the nearest allowed value: 4 becomes 10 and 45 becomes 30.
- 3Every path assigns
target, so the object never starts in an invalid or uninitialized state.
4The Default Constructor and Default Values
When no constructor is written, Java provides a no-parameter constructor, and the instance variables are set to default values according to the data type of the attribute. This constructor is called the default constructor. It exists only when the class has no constructors at all; once any constructor is written, Java no longer supplies one.
The default value for an attribute of type int is 0. The default value of an attribute of type double is 0.0. The default value of an attribute of type boolean is false. The default value of a reference type is null. These values also appear for any instance variable that a constructor forgets to set.
int is 0, double is 0.0, boolean is false, and any reference type is null.| Attribute type | Default value | Printed as |
|---|---|---|
int | 0 | 0 |
double | 0.0 | 0.0 |
boolean | false | false |
Reference type (String, any class) | null | null |
A Class With No Constructor
This class declares no constructor. Predict the output.
public class Gauge
{
private int reading;
private double scale;
private boolean active;
private String label;
public String report()
{
return reading + " " + scale + " " + active + " " + label;
}
}
0 0.0 false null
- 1Java supplies a constructor. When no constructor is written, Java provides a no-parameter default constructor, so
new Gauge()compiles. - 2Default values.
int→ 0,double→ 0.0,boolean→false, reference type →null.
If a class defines only Bike(int g, String c), then new Bike() does not compile: the default constructor is provided only when no constructor is written. To allow both, write the no-parameter constructor explicitly.
5Missing Initializations
An instance variable that no constructor statement sets keeps its default value. For numbers and booleans this may produce silently wrong results; for references it leaves null, which prints as "null" and causes a NullPointerException as soon as a method is called on it. The compiler does not warn about either.
A simple check catches these errors: list the instance variables at the top of the class, then confirm that every constructor assigns each one. Testing a new object immediately after construction, by printing all of its state, shows any variable that was missed.
An Instance Variable the Constructor Missed
The constructor sets title but forgets artist. What happens?
public class Song
{
private String title;
private String artist;
public Song(String t, String a)
{
title = t;
}
public String credit()
{
return title + " by " + artist;
}
public int artistLength()
{
return artist.length();
}
}
- 1The parameter
ais never stored, soartistkeeps its default value,null. - 2
credit()prints "Tidewater by null" because concatenatingnullgives the text "null". - 3
artistLength()callslength()onnulland throws aNullPointerException. - 4Fix. Add
artist = a;to the constructor.
NullPointerException. Every instance variable should be given a meaningful value by every constructor.Receiving a value as a parameter does nothing by itself. Unless the constructor assigns it to an instance variable, the value is lost when the constructor ends, and the instance variable keeps its default.
6Mutable Objects as Parameters
When a mutable object is a constructor parameter, the instance variable should be initialized with a copy of the referenced object. In this way, the instance variable does not hold a reference to the original object, and methods are prevented from modifying the state of the original object. Storing the parameter directly would make the instance variable an alias of the caller's object, so any later change the caller makes would silently change the new object too.
The copy is made by constructing a new object with the same data, for example new Point(p.getX(), p.getY()). Primitive parameters never need this, because the parameter already holds a copy of the value, and String parameters do not either, because strings are immutable.
| Parameter type | Store directly? | Reason |
|---|---|---|
Primitive (int, double, boolean) | Yes | The parameter is already a copy of the value |
String | Yes | Strings are immutable; no one can change them |
Mutable object (such as Point) | No: store a copy | Otherwise the caller can change the new object's state |
Sharing a Point by Accident
A Marker stores the Point passed to its constructor. Compare storing the reference with storing a copy.
public class Point
{
private int x;
private int y;
public Point(int x0, int y0)
{
x = x0;
y = y0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void moveTo(int newX, int newY)
{
x = newX;
y = newY;
}
}
public class Marker
{
private Point location;
public Marker(Point p)
{
location = p;
}
public String where()
{
return "(" + location.getX() + ", " + location.getY() + ")";
}
}
(9, 9)
public class Point
{
private int x;
private int y;
public Point(int x0, int y0)
{
x = x0;
y = y0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void moveTo(int newX, int newY)
{
x = newX;
y = newY;
}
}
public class Marker
{
private Point location;
public Marker(Point p)
{
location = new Point(p.getX(), p.getY());
}
public String where()
{
return "(" + location.getX() + ", " + location.getY() + ")";
}
}
(3, 4)
- 1Alias version.
location = p;stores the caller's reference. When the caller movesspot, the marker's location changes too: (9, 9). - 2Copy version. The constructor builds a new
Pointwith the same coordinates. Later changes tospotdo not reach it: (3, 4). - 3Strings need no copy, because
Stringobjects are immutable and cannot be changed through any reference.
location = p; makes the new object share the caller's Point. If the caller later moves that point, the new object's state changes without any of its own methods being called. Store a copy instead.
Four Habits for Constructors
1. Set Every Field
Each constructor gives every instance variable a value.
2. Assign, Do Not Redeclare
gears = g, not int gears = g.
3. Know the Defaults
0, 0.0, false, and null fill anything left unset.
4. Copy Mutable Parameters
Keep the object's state under its own control.
An object's state refers to its attributes and their values at a given time and is defined by instance variables belonging to the object, a has-a relationship. A constructor is used to set the initial state of an object, which should include initial values for all instance variables; when a constructor is called, memory is allocated for the object and the associated object reference is returned, and constructor parameters provide data to initialize instance variables. When a mutable object is a constructor parameter, the instance variable should be initialized with a copy of the referenced object. When no constructor is written, Java provides a no-parameter default constructor, and instance variables take default values: 0 for int, 0.0 for double, false for boolean, and null for reference types.