AP Computer Science A · Unit 3 lecture · Part 4 of 10 · 10 min

3.4 ConstructorsConstructors: every object starts ready

Mr. Thompkins
Every time you write new, Java builds an empty object and then runs a constructor to set it up. Your job as the author is to make sure no object ever leaves the constructor half finished.

A constructor looks like a method with two differences: its name is exactly the class name, and it has no return type, not even void. Its job is to give every instance variable a starting value, the object's initial state. Values that differ from object to object come in through parameters. Values that are always the same, like a count that starts at 0, are simply assigned.

?Wait, what does new actually do?
new creates a brand new object in memory, runs the matching constructor on it, and gives back a reference to it. Thermostat a = new Thermostat(); stores that reference in a. Without new, no object exists.

A class can have more than one constructor, as long as their parameter lists differ. That's called overloading, and Java chooses the constructor whose parameters match the arguments you pass. Below, new Thermostat() runs the first constructor and new Thermostat("lab", 18) runs the second.

1public class Thermostat2{3    private int target;4    private boolean heating;5    private String room;67    public Thermostat()18    {9        target = 20;10        room = "hall";11    }1213    public Thermostat(String room, int target)214    {15        this.room = room;316        this.target = target;317        heating = true;18    }1920    public String report()21    {22        return room + " " + target + " " + heating;23    }24}25// in a client class26Thermostat a = new Thermostat();427Thermostat b = new Thermostat("lab", 18);428System.out.println(a.report());29System.out.println(b.report());
  1. line 7 No-parameter constructor. It never sets heating
  2. line 13 Overloaded: same name, different parameter list
  3. line 15-16 this.room is the instance variable; room is the parameter
  4. line 26-27 Java picks the constructor whose parameters match
output › hall 20 false lab 18 true
Two overloaded constructors. The first never assigns heating.
aroom "hall"target 20heating falsebroom "lab"target 18heating truevariablestwo objects, two sets of datared: never assigned, so it kept the default
The two objects after construction. Each has its own copy of every instance variable.
?Wait, why does it say this.room = room?
The parameter is also named room, and inside the constructor the plain name room means the parameter. this.room means the instance variable of the object being built. So this.room = room copies the parameter into the object. You'll see this in full in 3.9.

Look at heating in the first object: the no-parameter constructor never touches it, and yet it prints false. That's because every instance variable gets a default value the moment the object is created, before any constructor code runs. If a constructor doesn't assign a variable, the default is what stays.

Instance variable typeDefault if never assigned
int0
double0.0
booleanfalse
String, or any class typenull
Default values of instance variables. Local variables get no defaults: you must assign them before use.

One more rule. If you write no constructor at all, Java quietly provides a no-parameter constructor that leaves every instance variable at its default. But once you write any constructor yourself, Java stops providing that one. So new Thermostat() works above only because we wrote a no-parameter constructor.

?Wait, what's null again?
null means "this reference points to no object". A String or other object variable that was never assigned holds null. Calling a method on it, like code.length(), throws a NullPointerException, because there's no object to run the method on.
Pause and think
With the Thermostat class above, what happens on the line Thermostat c = new Thermostat("den");?
I thought about it. Show me
It doesn't compile. Neither constructor takes just one String: one takes nothing and the other takes a String and an int. Java won't guess the missing value.
Find the bug
What does the client code print, and what's wrong with the constructor?
1public class Locker2{3    private int number;4    private String code;5    private boolean open;6    private double fee;78    public Locker(int n, String c)9    {10        number = n;11        String code = c;112    }1314    public String info()15    {16        return number + " " + code + " " + open + " " + fee;17    }18}19// in a client class20Locker k = new Locker(14, "7-2-9");21System.out.println(k.info());
  1. line 11 The word String makes a brand new local variable
output › 14 null false 0.0
  1. number = n; stores 14 in the instance variable number.
  2. String code = c; starts with a type, so it declares a new local variable named code that exists only inside the constructor. The instance variable code is never touched.
    Why?
    Any line that starts with a type declares a new variable. Inside the constructor, that local now hides the instance variable with the same name.
  3. open and fee are never assigned, so they keep their defaults: false and 0.0. The instance variable code keeps its default too: null.
  4. info() glues the four values together: "14 null false 0.0".
  5. The fix: write code = c; (no type) and assign the others on purpose, for example open = false; fee = 0.0;
    Why?
    Relying on defaults works, but writing the assignment shows the grader you set every instance variable.

Answer: It prints 14 null false 0.0. The line String code = c; made a local variable, so the instance variable code stayed null. Remove the word String.

Stuck? Get a hint
  1. Which lines in the constructor assign instance variables, and which declare something new?
  2. A line that starts with a type name declares a new variable.
  3. Anything never assigned keeps its default: int 0, double 0.0, boolean false, objects null.

When a parameter is a mutable object

A mutable object is one that has methods that change it, like a Plot you can widen. If a constructor receives a mutable object and stores the reference it was given, the new object and the caller share the same object. Later, when the caller changes it, the change shows up inside your object too. The safe habit, which the course asks for, is to store a copy: build a new object with the same values.

1public class Plot2{3    private int width;4    private int length;56    public Plot(int w, int l)7    {8        width = w;9        length = l;10    }1112    public void widen(int extra) { width += extra; }113    public int getWidth() { return width; }14    public int getLength() { return length; }15}1617public class Garden18{19    private Plot bed;2021    public Garden(Plot p)22    {23        bed = new Plot(p.getWidth(), p.getLength());224    }2526    public int bedArea()27    {28        return bed.getWidth() * bed.getLength();29    }30}31// in a client class32Plot p = new Plot(3, 4);33Garden g = new Garden(p);34p.widen(2);335System.out.println(p.getWidth() * p.getLength() + " "36    + g.bedArea());
  1. line 12 Plot is mutable: it has a method that changes it
  2. line 23 Store a copy, not the caller's object
  3. line 34 Widens the caller's plot only
output › 20 12
Garden stores its own copy of the plot it is given.
pPlot: 5 by 4gGardenbedPlot: 3 by 4new Plot(...) made a second objectp.widen(2) changed only the first plot
Two separate Plot objects. Changing the caller's plot can't reach into the garden.
Pause and think
Suppose Garden's constructor said bed = p; instead. What would the client print?
I thought about it. Show me
20 20. Then bed and p would refer to the same Plot, so widening p would also widen the garden's bed: 5 by 4 is 20 for both. Storing a copy is what keeps the garden at 12.
Check yourself
What is printed by the client code? (Kite's constructor sets color and length only.)
public class Kite
{
    private String color;
    private int length;
    private boolean flying;

    public Kite(String color)
    {
        this.color = color;
        length = 90;
    }

    public String toText()
    {
        return color + " " + length + " " + flying;
    }
}
// in a client class
Kite k = new Kite("red");
System.out.println(k.toText());
  1. Ared 90 false
  2. Bred 90 true
  3. Cred 90 null
  4. DNothing: flying is never set, so the class does not compile
Show the answer

A. flying is a boolean instance variable that the constructor never assigns, so it keeps the default false. The last choice is the top trap: an unassigned instance variable is legal and silently gets its default. Only local variables must be assigned before use.

Exam tip from Mr. T

The constructor point on the Class Design FRQ asks for every instance variable to be set correctly: from the parameters when the problem gives them, and to the right starting value otherwise. Write each assignment out. Never put a type in front of an instance variable inside the constructor.

  • A constructor has the class's name and no return type. It sets the initial state of every instance variable.
  • Overloaded constructors have different parameter lists. Java picks the one that matches the arguments.
  • Unassigned instance variables keep defaults: 0, 0.0, false, null. Java gives a no-parameter constructor only when you write none.
  • A line like String code = c; in a constructor makes a local variable, not the instance variable.
  • When a constructor receives a mutable object, store a copy so outside changes can't leak in.