Short on time? This page is the recap. For explanations and worked examples, use the full study guide.
Recap
- A class contains constructors that are called to create objects. They have the same name as the class.
- An object is typically created using the keyword
newfollowed by a call to one of the class’s constructors. - A constructor signature is the constructor’s name (the class name) plus the ordered list of parameter types. Constructors are overloaded when there are several with different signatures.
- Parameters allow constructors to accept values that establish the initial values of the attributes.
- A constructor argument is a value passed in when the constructor is called. Arguments must match the parameter types in order and number. They are passed by call by value: parameters are initialized with copies of the arguments.
- A variable of a reference type holds an object reference or, if there is no object,
null. - A constructor call interrupts the sequential execution; once its last statement runs, control returns to the point immediately after the call.
Key relationships
| Statement | Meaning |
|---|---|
Box b; |
declares a variable; no object |
new Box(3, 5) |
calls Box(int, int) and creates an object |
Box c = new Box(3, 5); |
declare, create and store the reference |
Box d = null; |
d refers to no object |
Box e = c; |
e and c refer to the same object |
c = new Box(9); |
c now refers to a different, new object |
| Call | Constructor used |
|---|---|
new Box() |
Box() |
new Box(4) |
Box(int) |
new Box(3, 5) |
Box(int, int) |
new Box(1, 2, 3) |
none: compile-time error |
new Box("x") or new Box(2.5) |
none: compile-time error |
Assumptions and conventions
- A constructor header has no return type, not even
void. - Only a statement containing
newcreates an object. ScannerandStringalso have constructors listed in the Java Quick Reference.- Calling a method on a
nullreference causes aNullPointerException(Topic 1.14).
Mistakes to avoid
- Confusing declaring a variable with creating an object.
- Leaving out
new. - Counting parameter names as part of the signature.
- Expecting a constructor to change the caller’s variable.
- Passing arguments that fit no constructor (wrong number or type).
- Thinking
b = a;makes a new object. - Forgetting that the constructor runs to its end before the next statement.
Quick self-check
- What is the signature of
public Box(int w, int h)? (Box(int, int)) - Which constructor does
new Box(7)call? (The one with a singleintparameter.) - After
Box b = null;what doesbrefer to? (No object.) - If a constructor adds 5 to its parameter, is the caller’s variable changed? (No: only the copy changes.)
- How many objects exist after
Box a = new Box(2); Box b = a;? (One.)
Next: practice questions.