AP Computer Science A · Class creation
Constructors
1What constructors do
A constructor sets up a new object's initial state. It:
- has the same name as the class;
- has no return type (not even
void); - runs automatically when
newis used.
public class Point {
private int x;
private int y; public Point(int initX, int initY) {
x = initX;
y = initY;
}
}
Point p = new Point(3, 4); allocates memory, runs the constructor with 3 and 4, and returns a reference to the object.
Check yourself
A constructor's return type is:
Show the answer
Not written (none)
No return type.
2Default values and the default constructor
If a constructor does not set an instance variable, it receives a default value:
int→ 0,double→ 0.0,boolean→ false, reference types (includingString) → null.
If a class has no constructor at all, Java provides a default (no-argument) constructor that leaves all instance variables at their defaults. As soon as you write any constructor, the default one is no longer provided.
Check yourself
An instance variable of type String not set by the constructor holds:
Show the answer
null
Reference default.
3Overloaded constructors
A class can have several constructors with different parameter lists:
public Point() {
x = 0;
y = 0;
}public Point(int initX, int initY) {
x = initX;
y = initY;
}
new Point() makes (0, 0); new Point(5, 2) makes (5, 2). Java picks the constructor whose parameters match the arguments' number, types and order.
Two overloaded constructors build objects with different starting values
Check yourself
A class has only Point(int a, int b). What happens with new Point()?
Show the answer
A compile-time error
No default constructor once one is written.
4Mutable objects as constructor parameters
If a constructor receives a reference to a mutable object (such as an array or ArrayList) and stores it directly, the new object and the caller share it: later changes by the caller affect the object.
To protect the object, make a copy:
public Roster(String[] names) {
list = new String[names.length];
for (int i = 0; i < names.length; i++) {
list[i] = names[i];
}
}
Strings are immutable, so storing a String reference is safe.
Check yourself
Why might a constructor copy an array parameter instead of storing it?
Show the answer
So later changes to the caller's array do not change the object
Avoid shared mutable state.
5Going deeper: defaults, overloading, and the errors that cost marks
A constructor sets up a new object's initial state. It runs once, when new is used.
- Same name as the class.
- No return type, not even
void. - Usually
public.
What new does
- Allocates memory for the object.
- Gives every instance variable its default value.
- Runs the constructor body.
- Returns a reference to the object.
Default values
int: 0.double: 0.0.boolean: false.- Any reference type (String, arrays, objects): null.
So an instance variable the constructor forgets to set is not random: it is 0, 0.0, false or null. A null String or array will cause a NullPointerException the first time a method is called on it.
The default constructor: if a class has no constructor at all, Java supplies one with no parameters that leaves everything at its default. As soon as you write any constructor, that automatic one is no longer provided.
public class Point {
private int x;
private int y;
public Point(int startX, int startY) {
x = startX;
y = startY;
}
}
Now new Point(3, 4) works, but new Point() does not compile.
Overloaded constructors: a class may have several, with different parameter lists.
public Point() {
x = 0;
y = 0;
}
public Point(int startX, int startY) {
x = startX;
y = startY;
}
Java chooses by matching the arguments: new Point() or new Point(3, 4).
Parameters against instance variables: parameters are local: they vanish when the constructor ends. Their values must be copied into instance variables to be kept.
Three classic errors
1. Re-declaring the variable
public Point(int startX, int startY) {
int x = startX; // declares a NEW local variable
int y = startY;
}
The instance variables stay 0.
2. Shadowing without this
public Circle(double radius) {
radius = radius; // assigns the parameter to itself
}
Fix: this.radius = radius;.
3. Adding a return type
public void Point(int startX, int startY) { ... }
This is an ordinary method named Point, not a constructor. The class then has only the default constructor.
Worked example (trace): what is printed?
public class Counter {
private int count;
private String label;
public Counter(int start) {
count = start;
}
public String describe() {
return label + " " + count;
}
}
// elsewhere:
Counter c = new Counter(5);
System.out.println(c.describe());
countis set to 5.labelwas never assigned: it is null.- Concatenating null gives the text "null".
- Output:
null 5. (Callinglabel.length()would instead throw a NullPointerException.)
Mutable objects as parameters: if a constructor stores a reference to an array or list passed in, the object and the caller share it. A later change by the caller alters the object's state.
public Scores(int[] values) {
data = new int[values.length];
for (int i = 0; i < values.length; i++) {
data[i] = values[i];
}
}
Copying element by element (a defensive copy) keeps the object's data independent. Strings need no copy, because they are immutable.
Initializing collections: an ArrayList or array instance variable must be created in the constructor (list = new ArrayList<String>();), not just declared. Otherwise it is null.
Objects are created only with new: declaring Point p; creates a variable, not an object.
Common mistakes
- Leaving an instance variable uninitialized and then calling a method on it.
- Assuming a no-argument constructor exists after writing another one.
- Arguments in the wrong order or of the wrong type.
- Storing a caller's array directly when independence is required.
Check yourself
A class defines exactly one constructor, public Dog(String name). What happens with Dog d = new Dog();?
Show the answer
The code does not compile
Java supplies a no-argument constructor only when the class defines none.
6For top marks
- Initialise every instance variable in every constructor, even if the value is 0 or an empty list.
- Use parameter names that differ from instance variable names, or use
this(see "Scope and the this keyword"). - Create collections in the constructor:
items = new ArrayList<String>();— forgetting this leavesitemsas null and causes a NullPointerException later. - Never write
voidbefore a constructor; that makes it an ordinary method.
public Playlist() { songs = new ArrayList<String>(); totalTime = 0; }
Check yourself
What happens if the constructor never creates the ArrayList songs and add is later called on it?
Show the answer
NullPointerException
songs is null.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera