Unit 1 · 20 min
1.13 Object Creation and Storage (Instantiation)
new plus a constructor builds an object; the variable stores a reference to it.
Summary, objectives and course and exam description (CED) codes
An object is created with the keyword new followed by a call to one of the class's constructors, which have the same name as the class. Java picks the constructor whose signature matches the arguments in number, order and type, and passes the arguments by call by value. A reference variable holds the new object's reference, or null if there is no object.
By the end of this session you can
- 1.13.A Identify, using its signature, the correct constructor being called.
- 1.13.B Develop code to declare variables of the correct types to hold object references.
- 1.13.C Develop code to create an object by calling a constructor.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. Constructors and constructor signatures
A class contains constructors that are called to create objects. They have the same name as the class 1.13.A.1.
A constructor signature is the constructor’s name (the same as the class name) plus the ordered list of parameter types. In the constructor header, the parameter list gives the type and the variable name of each value passed in 1.13.A.2.
Constructors are overloaded when a class has several constructors with different signatures 1.13.A.3. The Plant class used on these pages has 2 constructors:
| Constructor header | Signature | What it does |
|---|---|---|
public Plant(String n) |
Plant(String) |
name n, height starts at 0 |
public Plant(String n, int h) |
Plant(String, int) |
name n, height h |
Java picks the constructor by comparing the argument types with the parameter types, in order:
Plant p = new Plant("Fern", 30); // calls Plant(String, int)
Plant q = new Plant("Mint"); // calls Plant(String): height 0
System.out.println(p.getHeight());
System.out.println(q.getHeight());
Output:
30
0
Two constructors with the same parameter types, such as Box(int side) and Box(int len), do not compile, because their signatures are the same (Box(int)):
// does not compile
public class Box
{
private int size;
public Box(int side) { size = side; }
public Box(int len) { size = len; }
}
Real view:
error: constructor Box(int) is already defined in class Box
2. Variables that hold object references
A variable of a reference type holds an object reference or, if there is no object, null 1.13.B.1. The variable’s type is the class name.
Plant r = null; // r refers to no object
System.out.println(r);
r = new Plant("Sage", 8); // now r refers to a Plant
System.out.println(r.getName());
Output:
null
Sage
3. Creating an object with new
An object is typically created with the keyword new followed by a call to one of the class’s constructors 1.13.C.1. Parameters allow constructors to accept values that set the initial values of the object’s attributes 1.13.C.2.
Reading Plant p = new Plant("Fern", 30); part by part:
| Part | Meaning |
|---|---|
Plant (first) |
the class: the reference type of the variable |
p |
the variable that will hold the reference |
= |
assignment: store the reference in p |
new |
the keyword that creates the object |
Plant("Fern", 30) |
the constructor call: same name as the class; it runs, then control returns here |
"Fern", 30 |
the arguments, copied into the parameters n and h |
4. Constructor arguments
A constructor argument is a value passed into a constructor when it is called. The arguments must be compatible in order and number with the types in the parameter list of the constructor signature. Arguments are passed using call by value: the parameters are initialized with copies of the arguments 1.13.C.3. An int argument can go to a double parameter, because the int is widened to a double (topic 1.5).
public class Ticket
{
public Ticket(String event, double price)
{
System.out.println(event + " ticket: " + price);
}
public Ticket(double price)
{
System.out.println("General ticket: " + price);
}
public Ticket(int seat, String event)
{
System.out.println(event + " seat " + seat);
}
}
// in main
Ticket a = new Ticket("Gala", 40);
Ticket b = new Ticket(15.5);
Ticket c = new Ticket(12, "Gala");
Output:
Gala ticket: 40.0
General ticket: 15.5
Gala seat 12
new Ticket("Gala", 40) has a String then an int. Only Ticket(String, double) has a String first, and 40 is widened to 40.0.
Watch out: order matters. new Plant(30, "Fern") does not compile, because no Plant constructor takes an int first:
// does not compile
Plant f = new Plant(30, "Fern");
Real view:
error: incompatible types: int cannot be converted to String
The only Plant constructor with two parameters is Plant(String, int), and its first parameter needs a String, not the int 30.
5. Flow of control in a constructor call
A constructor call interrupts the sequential execution of statements: the program first runs the statements in the constructor. Once the last statement in the constructor has run, the flow of control returns to the point immediately after the constructor call 1.13.C.4.
Here a version of the Plant constructor also prints:
public class Plant
{
private String name;
private int height;
// a version of the Plant constructor that also prints
public Plant(String n, int h)
{
name = n;
height = h;
System.out.println("Made " + n);
}
public int getHeight()
{
return height;
}
}
// in main
System.out.println("Start");
Plant f = new Plant("Fern", 30);
System.out.println(f.getHeight());
Output:
Start
Made Fern
30
Start prints first. The constructor call then runs every statement in the constructor (printing Made Fern), and control comes back to the next line, which prints 30.
Lock it in: memory hooks
- Creating an objectnew + ClassName(arguments): new builds it, the constructor sets it up, the variable remembers where it is.
- Picking a constructorLine up the argument types with each parameter list, left to right. Only one should fit.
Common misconceptions
"You can call a constructor like a method, without new."
Not quite. An object is created with the keyword new followed by a constructor call: new Book("Dune", 412). Book("Dune", 412) on its own does not compile.
"Constructor arguments can be in any order."
Not quite. Arguments must be compatible with the parameter types in number and order. If the constructor is Plant(String n, int h), then new Plant(30, "Fern") does not compile.
"Plant p; creates a Plant."
Not quite. It only declares a variable that can hold a Plant reference. No object exists until new runs. Plant p = null; says clearly that p refers to no object yet.
Exam traps
- Java picks the constructor by comparing argument types with parameter types, in order. new Plant(30, "Fern") does not compile.
- An int argument can go to a double parameter (it is widened), so new Ticket("Gala", 40) can call Ticket(String event, double price).
- Two constructors with the same parameter types, such as Box(int side) and Box(int len), do not compile: parameter names are not part of the signature.
- Plant p = null; holds no object. Plant p = new Plant(""); holds an object whose name is the empty string.
2PracticeRecall it, then check yourself
In 30 seconds
- Constructors are called to create objects and have the same name as the class.
- A constructor signature is the constructor name plus the ordered list of parameter types; several signatures means overloaded constructors.
- A reference variable holds an object reference, or null if there is no object.
- Create an object with new followed by a constructor call; parameters set the initial values of the attributes.
- Arguments must match the parameter types in number and order and are passed by call by value.
- A constructor call runs every statement in the constructor, then control returns right after the call.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 4 questions
Checkpoint: Object Creation and Storage (Instantiation)
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.
-
Ticket constructors Constructor Ticket(String event, double price) Ticket(double price) Ticket(int seat, String event) -
Plant class (implementations not shown) Constructor or method What it does public Plant(String n) Sets the name to n and the height to 0 public Plant(String n, int h) Sets the name to n and the height to h public String getName() Returns the name public int getHeight() Returns the height public void grow(int cm) Adds cm to the height
3PrevailLock it in for exam day
By the numbers
- Parts of a constructor signature two parts CED 1.13.A.2
- the constructor namesame as the class name
- the ordered list of parameter types
- Ways arguments must be compatible with the parameter list two ways CED 1.13.C.3
- number
- orderof the types
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 -
Constructor signaturetap to flip
The constructor's name (the class name) plus the ordered list of parameter types, such as Plant(String, int).
Example and CED codes -
newtap to flip
The keyword that creates an object. It is followed by a call to one of the class's constructors.
Example and CED codes -
Instantiationtap to flip
Creating an object (an instance) of a class with new and a constructor call.
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 -
Argumenttap to flip
A value passed into a method or constructor when it is called.
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 -
Call by valuetap to flip
The way Java passes arguments: each parameter is initialized with a copy of the argument.
Example and CED codes -
Overloadingtap to flip
Having several methods (or constructors) with the same name but different signatures.
Example and CED codes
Questions students ask
What is a constructor in Java?
A constructor is called to create an object of a class. It has the same name as the class, and its parameters let it set the initial values of the object's attributes.
How do you create an object in Java?
Use the keyword new followed by a call to one of the class's constructors, and store the reference in a variable of the class type: Plant p = new Plant("Fern", 30);.
What are overloaded constructors?
A class has overloaded constructors when it has several constructors with different signatures, such as Plant(String n) and Plant(String n, int h). Java picks one by matching the arguments.
What does null mean for an object variable?
null means the reference variable is not associated with any object. Plant r = null; declares a variable that can hold a Plant reference but refers to no object yet.