Unit 3 · 20 min
3.4 Constructors
The constructor's job is to give a brand new object a complete, valid starting state.
Summary, objectives and course and exam description (CED) codes
An object's state is its attributes and their values at a given time, stored in the object's instance variables (a has-a relationship). A constructor sets the initial state: when it is called, memory is allocated for the object and a reference to it is returned. If you write no constructor, Java provides a no-parameter default constructor that sets instance variables to default values.
By the end of this session you can
- 3.4.A Develop code to declare instance variables for the attributes, to be initialized in the body of the constructors of a class.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. State: what an object has, right now
An object’s state is its attributes and their values at a given time. The state is defined by the instance variables that belong to the object 3.4.A.1. This is a has-a relationship: a player has a name, has a score and has a level 3.4.A.1.
public class Player
{
private String name;
private int score;
private int level;
/** Creates a player at level 1 with a score of 0 */
public Player(String playerName)
{
name = playerName;
score = 0;
level = 1;
}
/** Creates a player at startLevel with a score of 0 */
public Player(String playerName, int startLevel)
{
name = playerName;
score = 0;
level = startLevel;
}
public void addPoints(int points)
{
score += points;
if (score >= 100)
{
level++;
score -= 100;
}
}
public String getName()
{
return name;
}
public int getScore()
{
return score;
}
public int getLevel()
{
return level;
}
public String toString()
{
return name + " L" + level + " " + score + " pts";
}
}
Player ana = new Player("Ana");
System.out.println(ana);
ana.addPoints(70);
System.out.println(ana);
ana.addPoints(45);
System.out.println(ana);
Output:
Ana L1 0 pts
Ana L1 70 pts
Ana L2 15 pts
Background: println(ana) shows the text built by the class’s toString method. You will read toString in class code, but writing one is outside the AP® exam.
The state changes over time:
| Moment | name | score | level |
|---|---|---|---|
After new Player("Ana") |
“Ana” | 0 | 1 |
After addPoints(70) |
“Ana” | 70 | 1 |
After addPoints(45) |
“Ana” | 15 | 2 |
2. Writing a constructor
A constructor sets the initial state of an object, and that should include an initial value for every instance variable 3.4.A.2. Constructor parameters, if there are any, provide the data used to initialize the instance variables 3.4.A.2.
When a constructor is called with new, memory is allocated for the object and the reference to the new object is returned 3.4.A.2. The variable stores that reference, not the object itself.
Player p1 = new Player("Ana");
Player p2 = new Player("Ben", 5);
System.out.println(p1.getLevel() + " " + p2.getLevel());
Output:
1 5
Memory after these lines:
p1 [ ref ] ---> Player object: name "Ana" score 0 level 1
p2 [ ref ] ---> Player object: name "Ben" score 0 level 5
Player has two constructors with different parameter lists (overloaded constructors). Java chooses the one whose parameters match the arguments.
Watch out: a constructor has the same name as the class and no return type. If you write void, Java treats it as a method, not a constructor:
public class Pet
{
private String name;
public void Pet(String petName)
{
name = petName;
}
}
Pet cat = new Pet("Miso");
Compiler says:
error: constructor Pet in class Pet cannot be applied to given types;
3. Mutable object parameters: store a copy
When a mutable object (an object whose state can change) is a constructor parameter, the instance variable should be initialized with a copy of the object. Then the instance variable does not hold a reference to the original object, and outside code cannot change the state of your object through the original 3.4.A.3.
Here is a mutable class:
public class Location
{
private int row;
private int col;
public Location(int r, int c)
{
row = r;
col = c;
}
public int getRow()
{
return row;
}
public int getCol()
{
return col;
}
public void moveTo(int r, int c)
{
row = r;
col = c;
}
public String toString()
{
return "(" + row + ", " + col + ")";
}
}
Version 1 (risky): the constructor stores the same reference.
public class Robot
{
private Location home;
public Robot(Location start)
{
home = start;
}
public String homeText()
{
return home.toString();
}
}
Location spot = new Location(2, 3);
Robot bot = new Robot(spot);
spot.moveTo(9, 9);
System.out.println(bot.homeText());
Output:
(9, 9)
spot [ ref ] ---+
+---> Location object: row 9, col 9
home [ ref ] ---+ (one object, two references)
Version 2 (correct): the constructor makes a new Location with the same values.
public class Robot
{
private Location home;
public Robot(Location start)
{
home = new Location(start.getRow(), start.getCol());
}
public String homeText()
{
return home.toString();
}
}
Location spot = new Location(2, 3);
Robot bot = new Robot(spot);
spot.moveTo(9, 9);
System.out.println(bot.homeText());
Output:
(2, 3)
spot [ ref ] ---> Location object: row 9, col 9
home [ ref ] ---> Location object: row 2, col 3 (the robot's own copy)
String objects are immutable, so a constructor can store a String parameter directly: nobody can change that string.
4. The default constructor and default values
When no constructor is written, Java provides a no-parameter constructor, called the default constructor, and the instance variables are set to default values according to their data types 3.4.A.4.
| Type of attribute | Default value 3.4.A.5 |
|---|---|
int |
0 |
double |
0.0 |
boolean |
false |
any reference type (such as String) |
null |
public class Settings
{
private int volume;
private double brightness;
private boolean muted;
private String theme;
// no constructor written: Java provides Settings()
public String toString()
{
return volume + " " + brightness + " " + muted + " " + theme;
}
}
Settings s = new Settings();
System.out.println(s);
Output:
0 0.0 false null
Watch out: once you write any constructor, Java no longer provides the default constructor. Player has two constructors, but neither has zero parameters:
Player p = new Player();
Compiler says:
error: no suitable constructor found for Player(no arguments)
Watch out: a constructor that does not set an instance variable leaves it at its default value. A forgotten String is null, and calling a method on it later (such as name.length()) causes a NullPointerException.
Lock it in: memory hooks
- StateState is a snapshot: every instance variable and its value right now.
- Default valuesNumbers start at zero (0 or 0.0), booleans start false, references start null.
- Mutable parametersCopy what can change: new Location(start.getRow(), start.getCol()), not home = start.
Common misconceptions
"A constructor needs the return type void."
Not quite. A constructor has no return type at all. If you write void, Java treats it as an ordinary method that happens to have the class name, and it is never called by new.
"Java always gives every class a no-parameter constructor."
Not quite. Java provides the default constructor only when you write no constructor. As soon as you write one, new ClassName() with no arguments works only if you wrote a no-parameter constructor yourself.
"Storing a parameter object in an instance variable makes a copy of it."
Not quite. Assigning a reference copies the reference, not the object. To protect a mutable object, the constructor must create a new object with the same values.
Exam traps
- A constructor with void in front is not a constructor.
- Writing any constructor removes the default constructor: new Player() then does not compile unless you wrote Player().
- A String instance variable that the constructor forgets to set is null, not the empty string.
- home = start stores the same object; later changes to start also change home.
2PracticeRecall it, then check yourself
In 30 seconds
- State = the object's attributes and their values at a given time; the object has-a each instance variable.
- A constructor sets the initial state and should give every instance variable an initial value.
- Calling a constructor allocates memory for the object and returns a reference to it.
- Constructor parameters provide the data used to initialize instance variables.
- For a mutable object parameter, store a copy of the object, not the original reference.
- No constructor written: Java provides a default constructor; int 0, double 0.0, boolean false, references null.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 5 questions
Checkpoint: Constructors
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
- Default values of attributes four defaults CED 3.4.A.5
- int0
- double0.0
- booleanfalse
- reference typenull
- What happens when a constructor is called three steps CED 3.4.A.2
- memory is allocated for the object
- the constructor body sets the initial state
- the object reference is returned
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
Constructortap to flip
Code in a class that is called to create an object. It has the same name as the class and sets the object's initial attribute values.
Example and CED codes -
Default constructortap to flip
The no-parameter constructor Java provides when a class has no constructor written; it sets instance variables to default values.
Example and CED codes -
State (of an object)tap to flip
An object's attributes and their values at a given time, stored in the object's instance variables.
Example and CED codes -
Instance variabletap to flip
An attribute declared in a class outside any method or constructor, whose value is unique to each object of the class.
Example and CED codes -
nulltap to flip
A special literal meaning a reference variable is not associated with any object.
Example and CED codes -
Object referencetap to flip
The value a reference variable holds: it can be thought of as the memory address of the object.
Example and CED codes -
Parametertap to flip
A variable declared in the header of a method or constructor. It receives the value passed in and can be used in the body.
Example and CED codes
Questions students ask
What does a constructor do in Java?
A constructor sets the initial state of a new object, giving initial values to its instance variables. When it is called with new, memory is allocated for the object and a reference to the object is returned.
What is a default constructor?
It is the no-parameter constructor Java provides when a class has no constructor written. It sets each instance variable to the default value for its type: 0, 0.0, false or null.
Why should a constructor copy a mutable object parameter?
If the constructor stores the same reference, the caller can still change the object later and the change appears inside your object. Storing a new copy keeps the object's state under the class's control.
Can a class have more than one constructor?
Yes. Constructors can be overloaded: each has a different parameter list, and Java chooses the one that matches the arguments in the new expression.