A constructor runs when new creates an object: it has the class's name and no return type, and it gives each instance variable a starting value, usually from its parameters. An instance variable it leaves alone keeps its default value: 0, 0.0, false or null. A class can have several constructors with different parameter lists, and a parameter named like an instance variable hides it unless you write this..
Quick check
In a class, what does private int score; declare, and which code can use score directly?Show answerHide answer
An instance variable: every object of the class gets its own
score. Because it isprivate, only code inside the class can use it directly.In Dog d = new Dog();, what does the variable d hold?Show answerHide answer
A reference to the new
Dogobject thatnewcreated.A class has private boolean done; and its constructor never mentions done. What does done hold in a new object?Show answerHide answer
false, the default value for abooleaninstance variable.
Know these already? Jump to the practice questions
What you'll be able to do
- State the rules for a constructor header.
- Determine a new object's state by tracing its constructor.
- State the default value of an unset instance variable.
- Identify which overloaded constructor a
newcall runs. - Explain why
name = name;leaves an instance variable unset.
Key terms
Constructor
Code with the class's name and no return type that runs once each time new creates an object, setting its initial state.
- In plain English
- The setup code for a new object.
- Don't write
- "A constructor returns
void."
Default value
The value an instance variable holds if it is never assigned: 0, 0.0, false or null, by type.
- In plain English
- What an instance variable holds if nobody sets it.
- Don't write
- "An unset instance variable holds a random value."
Shadowing
A parameter with the same name as an instance variable hides it, so the plain name means the parameter.
- In plain English
- The nearer variable wins the name.
- Don't write
- "
name = name;copies the parameter into the instance variable."
What does a constructor do?
A constructor runs once, when new creates an object. Its header looks like a method header except that its name is exactly the class name and it has no return type, not even void. Constructors are usually public, so code outside the class can create objects.
public class Lamp
{
private int watts;
private boolean on;
public Lamp(int w, boolean o)
{
watts = w;
on = o;
}
}
new Lamp(40, true) passes the arguments 40 and true into the parameters w and o, so watts becomes 40 and on becomes true. Parameters disappear when the constructor ends, but instance variables last as long as the object, which is why the constructor copies each parameter into one.
Key idea
A constructor's job is to copy or compute a starting value for each instance variable.
Check yourself
Show answerHide answer
Adding void gives it a return type, so it is an ordinary method that shares the class's name; new Lamp(40, true) cannot use it.
What does an instance variable hold if the constructor skips it?
Before the constructor body runs, every instance variable already holds its default value. Learn this: the defaults are not on the Java Quick Reference.
| Type | Default value |
|---|---|
int | 0 |
double | 0.0 |
boolean | false |
String or any other reference | null |
The body replaces the values it assigns; anything it never mentions keeps its default. If a class has no constructor at all, Java supplies a no-argument one, and every instance variable without an initial value in its declaration holds its default.
Defaults apply to instance and static variables, but never to local variables. A local variable gets no default, and using it before you assign it is a compile-time error.
Check yourself
Show answerHide answer
null, the default value for a reference.
How does Java choose between overloaded constructors?
Overloaded constructors are constructors in one class with different parameter lists. Java runs the one whose parameter list fits the arguments: their number, types and order.
public Lamp()
{
watts = 60;
}
Added to Lamp, this gives two constructors. new Lamp() runs this one: watts becomes 60 and on keeps its default, false. new Lamp(40, true) runs the two-parameter one.
Two constructors with the same parameter types in the same order cause a compile-time error; parameter names don't count. Once you write any constructor, Java stops supplying the automatic no-argument one, so new Lamp() compiles only if you write Lamp() yourself.
Check yourself
Show answerHide answer
Pen(String c, int s): there are two arguments, a String then an int.
Why doesn't name = name; set the instance variable?
Inside a constructor, a parameter shadows an instance variable with the same name. In name = name; both sides mean the parameter, so the line copies the parameter into itself. It compiles, but the instance variable keeps its default, null.
Two fixes work:
- Write
this.name = name;.this.namemeans the current object's instance variable, and the plainnamemeans the parameter. - Give the parameter a different name, such as
n, and writename = n;.
The note on scope, access and the this keyword covers this in full.
Check yourself
Show answerHide answer
The left side, this.price.
Worked example 1: Trace a constructor
Question: What is printed when this code runs?
public class Ticket
{
private String event;
private int row;
private double price;
private boolean scanned;
public Ticket(String e, int r)
{
event = e;
row = r;
price = 40.0 - 2 * r;
}
public String getInfo()
{
return event + " row " + row + " " + price + " " + scanned;
}
}
Ticket t = new Ticket("Jazz", 7);
System.out.println(t.getInfo());
What tells you the method
A new call then a method that reads the state, so trace the instance variables.
Step 1: Trace the body with
e= "Jazz" andr= 7, starting from the defaults.After eventrowpricescanneddefaults null0 0.0 falseevent = e;"Jazz" 0 0.0 falserow = r;"Jazz" 7 0.0 falseprice = 40.0 - 2 * r;"Jazz" 7 26.0 falseWhyDefaults are in place before the body runs.
2 * ris 14, and 40.0 − 14 is thedouble26.0. Nothing setsscanned.Step 2: Build the string.
getInfojoins the values in order.WhyA
doubleprints with a decimal point, and abooleanasfalse.
Check it
With r = 0 the price would be 40.0, the top price, so 26.0 for row 7 is sensible.
Answer
Jazz row 7 26.0 false
Worked example 2: Design an overloaded constructor
Question: Design a second constructor for this class so that new Timer(135) makes a timer of 2 minutes 15 seconds. Then state what System.out.println(new Timer(135).getTime()); prints.
public class Timer
{
private int minutes;
private int seconds;
public Timer(int m, int s)
{
minutes = m;
seconds = s;
}
public String getTime()
{
return minutes + ":" + seconds;
}
}
What tells you the method
A design task: plan, write the header, then trace.
Step 1: State the input, the output and the plan.
The input is a number of seconds; the output is both instance variables set. Minutes are
total / 60; the seconds left over aretotal % 60.Whyintdivision drops the remainder, and%gives exactly that remainder.Step 2: Write the header and body.
public Timer(int total) { minutes = total / 60; seconds = total % 60; }WhyOne
intparameter differs from the existing two-parameter list, so the overload is legal.Step 3: Trace it on 135.
135 / 60is 2 and135 % 60is 15, sogetTime()returns "2:15".WhyTracing on a stated input tests the design.
Check it
On 59 the values are 0 and 59; on 60, the boundary, they are 1 and 0.
Answer
2:15
Worked example 3: Fix a shadowed parameter
Question: The statements Book b = new Book("Dune", 412); and System.out.println(b.getTitle()); print null. Which change makes them print Dune?
1: public class Book
2: {
3: private String title;
4: private int pages;
5:
6: public Book(String title, int p)
7: {
8: title = title;
9: pages = p;
10: }
11:
12: public String getTitle()
13: {
14: return title;
15: }
16: }
- A) Change line 8 to
this.title = title; - B) Change line 8 to
title = this.title; - C) Change line 6 to
public void Book(String title, int p) - D) Change line 14 to
return this.title;
What tells you the method
A parameter has the same name as an instance variable, so check which variable each title means.
Step 1: Find the fault.
In line 8 both
titles are the parameter, so the instance variable staysnull.WhyThe parameter shadows the instance variable inside the constructor.
Step 2: Test each option.
A stores "Dune" in the instance variable. B copies
nullinto the parameter. C makes the constructor a method, sonew Book("Dune", 412)no longer compiles. D reads the instance variable, which is stillnull.WhyOnly assigning to
this.titlesets the object's state.
Check it
With A, getTitle() returns the instance variable, now "Dune".
Answer
A
Your turn
Question: What is printed when this code runs?
public class Badge
{
private String name;
private int level;
public Badge(String n)
{
name = n;
level = 1;
}
public Badge(String n, int lv)
{
name = n;
level = lv;
}
public String show()
{
return name + level;
}
}
Badge a = new Badge("Kai");
Badge b = new Badge("Ana", 4);
System.out.println(a.show() + " " + b.show());
Step 1: Match the first call.
new Badge("Kai")has oneStringargument, so it runsBadge(String n):nameis "Kai" andlevelis 1.Step 2: Your go: match the second call, then build the printed line.
Show the full solutionHide the solution
Step 2. new Badge("Ana", 4) has a String then an int, so it runs Badge(String n, int lv): name is "Ana" and level is 4. a.show() is "Kai1" and b.show() is "Ana4", joined by a space.
Answer: Kai1 Ana4
Traps
Trap
Every variable starts at 0 or null if you don't set it.
It seems right because instance variables do. But local variables get no default, so reading one before assigning it is a compile-time error.
Inside a constructor, does int total; total = total + 5; compile?
No: total is a local variable with no value yet.
Trap
Writing a constructor with parameters keeps the automatic no-argument one.
It seems right because a class with no constructor allows new Ticket(). But Java supplies that constructor only when a class declares none, so after you write Ticket(String e, int r), new Ticket() fails to compile.
Class Cup has only Cup(int size). Does new Cup() compile?
No: Cup has no no-argument constructor.
What's examined
On the AP® Computer Science A exam (Unit 3: Class Creation), multiple-choice questions ask which constructor a call runs, what state a new object has, or which code completes a constructor. The class design free-response question has you write a class, constructor included, so make sure the constructor sets every instance variable.
Practice questions
- Recall Which is a valid constructor header for a class named
Robot?
- A)
public void Robot(int id) - B)
public Robot(int id) - C)
public robot(int id) - D)
public Robot Robot(int id)
Show answer
Answer: B. A constructor has exactly the class name and no return type.
Why the others are wrong:
- A has the return type
void, so it is a method. - C misspells the class name: Java is case-sensitive, so
robotis notRobot. - D has the return type
Robot, so it is a method.
- Recall Name the default value of a
Stringinstance variable that no constructor sets.
Show answer
Answer: null
Marking points:
- A
Stringvariable holds a reference, and an unset reference instance variable isnull.
- Apply What is printed?
public class Lamp
{
private int watts;
private boolean on;
public Lamp()
{
watts = 60;
}
public Lamp(int w, boolean o)
{
watts = w;
on = o;
}
public String status()
{
return watts + " " + on;
}
}
Lamp x = new Lamp();
Lamp y = new Lamp(40, true);
System.out.println(x.status());
System.out.println(y.status());
Show answer
Answer: 60 false then 40 true on the next line.
Marking points:
Lamp()setswattsto 60;onkeeps its default,false.Lamp(40, true)sets both instance variables from the arguments.
- Exam-style The constructor should set both instance variables from its parameters. Give the number of the line that stops it working.
1: public class Crate
2: {
3: private int width;
4: private int depth;
5:
6: public Crate(int w, int d)
7: {
8: width = w;
9: d = depth;
10: }
11: }
Show answer
Answer: Line 9.
Marking points:
- Line 9 copies the instance variable (still 0) into the parameter, the wrong way round.
- The fix is
depth = d;; afternew Crate(3, 5),depthwould then be 5.
- Exam-style A class
Songhas exactly two constructors:Song(String t)andSong(String t, int s). Which statement causes a compile-time error?
- A)
Song a = new Song("Echo"); - B)
Song b = new Song("Echo", 200); - C)
Song c = new Song(); - D)
Song d = new Song("Echo", 3 / 2);
Show answer
Answer: C. The class declares constructors, so Java supplies no no-argument one, and none was written.
Why the others are wrong:
- A matches
Song(String t). - B matches
Song(String t, int s). - D also matches it:
3 / 2isintdivision, giving theint1, not 1.5.
- Exam-style What is printed?
public class Recipe
{
private String dish;
private int servings;
private double cups;
private int extra;
public Recipe(String d, int people)
{
dish = d;
servings = people / 4;
cups = people / 4.0;
}
public String summary()
{
return dish + ": " + servings + ", " + cups + ", " + extra;
}
}
Recipe r = new Recipe("soup", 10);
System.out.println(r.summary());
Show answer
Answer: soup: 2, 2.5, 0
Marking points:
10 / 4isintdivision, soservingsis 2.10 / 4.0isdoubledivision, socupsis 2.5.- Nothing sets
extra, so it keeps its default, 0.
- Exam-style A class has
private String owner;andprivate double balance;. Its constructor header ispublic Account(String owner, double start). Which code segment completes the constructor so both instance variables are set from the parameters?
- A)
owner = owner;thenbalance = start; - B)
this.owner = owner;thenstart = balance; - C)
this.owner = owner;thenthis.balance = balance; - D)
this.owner = owner;thenbalance = start;
Show answer
Answer: D. this.owner is the instance variable, and balance has no parameter shadowing it.
Why the others are wrong:
- A assigns the parameter
ownerto itself, so the instance variable staysnull. - B copies the instance variable into the parameter, the wrong way round.
- C uses the instance variable's name where the parameter
startbelongs, sobalanceis assigned to itself and stays 0.0.
- Apply How many times does a constructor run when this code executes?
Lamp a = new Lamp();
Lamp b = a;
Lamp c = new Lamp(25, false);
Show answer
Answer: 2
Marking points:
- A constructor runs once for each
new, and there are two. Lamp b = a;copies a reference; it creates no object.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- A constructor has the class's name and no return type, and runs once per
new. - Unset instance variables hold 0, 0.0,
falseornull; local variables get no default. - Java picks the overloaded constructor whose parameter list matches the arguments.
- Writing any constructor removes the automatic no-argument one.
- When a parameter shares an instance variable's name, assign with
this.name = name;.