AP Computer Science A · Study guide

Constructor State Initialization

AP® Computer Science A · Class Creation

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.

Big Picture

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.

Figure 1. An object's state refers to its attributes and their values at a given time, defined by its instance variables. This is a has-a relationship.

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.

Figure 2. When a constructor is called, memory is allocated for the object, the constructor sets its initial state, and the associated object reference is returned.
Constructor factDetail
PurposeSet the initial state of an object, including initial values for all instance variables
What a call doesAllocates memory for the object and returns the associated object reference
ParametersIf specified, provide data to initialize instance variables
No constructor writtenJava provides a no-parameter default constructor that uses default values
Worked Example 1 Writing a constructor

Initializing Every Instance Variable

Write a constructor for Bike that takes the number of gears and a color, and starts the odometer at 0.

The Bike class and a short program
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";
    }
}
Output
21-speed teal, 0.0 km
21-speed teal, 12.5 km
  1. 1Parameters supply data. g and c provide the values for gears and color.
  2. 2Fixed starting value. Every new bike starts with odometerKm 0.0, so that value is written in the constructor, not passed in.
  3. 3Every instance variable is set. The object starts in a complete, meaningful state.
Result: The output is 21-speed teal, 0.0 km, then 21-speed teal, 12.5 km. A constructor sets the initial state of an object, which should include initial values for all instance variables.
Common Mistake 1 · Declaring a Local Variable Instead of Assigning the Field

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.

Worked Example 2 Overloaded constructors

A Default Bike and a Custom Bike

Classes often offer several constructors. Predict the output.

A Bike class with two constructors
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;
    }
}
Output
1-speed black
7-speed orange
  1. 1new Bike() runs the no-parameter constructor, which chooses sensible starting values itself.
  2. 2new Bike(7, "orange") runs the two-parameter constructor.
  3. 3Both constructors set every instance variable, so either way the object is complete.
Result: The output is 1-speed black and 7-speed orange. Writing several constructors gives users of the class different ways to create objects, each producing a fully initialized state.
Worked Example 3 Validating in the constructor

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.

A Thermostat class that checks its parameter
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;
    }
}
Output
21
10
30
  1. 1Valid input is stored as given: 21.
  2. 2Out-of-range input is replaced by the nearest allowed value: 4 becomes 10 and 45 becomes 30.
  3. 3Every path assigns target, so the object never starts in an invalid or uninitialized state.
Result: The output is 21, 10, 30. A constructor can contain any statements, including selection, to make sure the initial state is valid.

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.

Figure 3. The default value for an attribute of type int is 0, double is 0.0, boolean is false, and any reference type is null.
Attribute typeDefault valuePrinted as
int00
double0.00.0
booleanfalsefalse
Reference type (String, any class)nullnull
Worked Example 4 The default constructor

A Class With No Constructor

This class declares no constructor. Predict the output.

A Gauge class without a constructor
public class Gauge
{
    private int reading;
    private double scale;
    private boolean active;
    private String label;

    public String report()
    {
        return reading + " " + scale + " " + active + " " + label;
    }
}
Output
0 0.0 false null
  1. 1Java supplies a constructor. When no constructor is written, Java provides a no-parameter default constructor, so new Gauge() compiles.
  2. 2Default values. int → 0, double → 0.0, boolean → false, reference type → null.
Result: The output is 0 0.0 false null. The default constructor sets instance variables to default values according to their data types.
Common Mistake 2 · Expecting the Default Constructor After Writing Another

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.

Worked Example 5 Forgetting a field

An Instance Variable the Constructor Missed

The constructor sets title but forgets artist. What happens?

A constructor with a missing assignment
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();
    }
}
  1. 1The parameter a is never stored, so artist keeps its default value, null.
  2. 2credit() prints "Tidewater by null" because concatenating null gives the text "null".
  3. 3artistLength() calls length() on null and throws a NullPointerException.
  4. 4Fix. Add artist = a; to the constructor.
Result: The program prints Tidewater by null and then stops with a NullPointerException. Every instance variable should be given a meaningful value by every constructor.
Common Mistake 3 · Forgetting a Parameter Assignment

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.

Figure 4. When a mutable object is a constructor parameter, the instance variable should be initialized with a copy, so methods outside cannot change the new object's state through the original.
Parameter typeStore directly?Reason
Primitive (int, double, boolean)YesThe parameter is already a copy of the value
StringYesStrings are immutable; no one can change them
Mutable object (such as Point)No: store a copyOtherwise the caller can change the new object's state
Worked Example 6 Mutable parameters

Sharing a Point by Accident

A Marker stores the Point passed to its constructor. Compare storing the reference with storing a copy.

Storing the reference (alias)
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() + ")";
    }
}
Output
(9, 9)
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 = new Point(p.getX(), p.getY());
    }

    public String where()
    {
        return "(" + location.getX() + ", " + location.getY() + ")";
    }
}
Output
(3, 4)
  1. 1Alias version. location = p; stores the caller's reference. When the caller moves spot, the marker's location changes too: (9, 9).
  2. 2Copy version. The constructor builds a new Point with the same coordinates. Later changes to spot do not reach it: (3, 4).
  3. 3Strings need no copy, because String objects are immutable and cannot be changed through any reference.
Result: The alias version prints (9, 9) and the copy version prints (3, 4). When a mutable object is a constructor parameter, initializing the instance variable with a copy keeps the new object's state under its own control.
Common Mistake 4 · Storing a Caller's Mutable Object Directly

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.

Core Synthesis

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.