Object Instantiation
Creating objects with new and a constructor call: how arguments become the starting values of an object's attributes, how arguments are passed by value, and how a constructor call temporarily takes over the flow of a program.
Instantiation means creating an instance, an object, of a class. An object is typically created using the keyword new followed by a call to one of the class's constructors. The constructor's parameters accept values that establish the initial values of the object's attributes. The arguments must be compatible in order and number with the constructor's parameter list, they are passed by value, and the constructor call interrupts the program until the constructor finishes.
1Creating an Object
The statement Plant fern = new Plant("fern", 30); does three things. On the left, it declares a reference variable named fern of type Plant. On the right, the keyword new tells Java to create a brand-new object, and Plant("fern", 30) calls a constructor to set it up. Finally, the assignment stores a reference to the new object in fern.
The declaration and the creation can also be written separately: Plant fern; on one line and fern = new Plant("fern", 30); later. Either way, no object exists until new is evaluated. Declaring a variable reserves a place for a reference; only new with a constructor call produces an object to put there.
Once the object exists, the program interacts with it through the variable: fern.grow(5) changes its height and fern.getHeight() reports it. The constructor's work is finished the moment the object is created; everything after that happens through the object's methods.
new followed by a call to one of the class's constructors.| Part | Example | Role |
|---|---|---|
| Declared type and name | Plant fern | Creates a reference variable |
new | new | Creates a new object |
| Constructor call | Plant("fern", 30) | Sets the new object's starting attributes |
| Assignment | = | Stores the reference to the new object in the variable |
Building Plants and Reading Their State
The class Plant is given. Predict the output.
public class Plant
{
private String name;
private int height;
public Plant(String n, int h)
{
name = n;
height = h;
}
public void grow(int cm)
{
height = height + cm;
}
public String getName()
{
return name;
}
public int getHeight()
{
return height;
}
}
fern 35
moss 4
- 1Two constructor calls.
fernstarts with name "fern" and height 30;mosswith "moss" and 4. - 2
fern.grow(5)raises onlyfern's height, to 35. - 3Reading state. The getter methods return each object's current values.
Creating an Object Later and Replacing It
Predict the output.
public class Plant
{
private String name;
private int height;
public Plant(String n, int h)
{
name = n;
height = h;
}
public void grow(int cm)
{
height = height + cm;
}
public String getName()
{
return name;
}
public int getHeight()
{
return height;
}
}
sage 10
dill 3
- 1
Plant p;declares the variable; no object exists yet. - 2
p = new Plant("sage", 6);creates the first plant;grow(4)raises its height to 10. - 3
p = new Plant("dill", 3);creates a second, separate plant with its own starting values and stores its reference inp. The sage plant is not changed;psimply refers to a different object now.
new builds a fresh object with values from its own constructor call.Plant fern = Plant("fern", 30); does not compile: without new, Java looks for a method named Plant. To call a constructor and create an object, always write new before the class name.
2Setting the Object's Starting Values
Parameters allow constructors to accept values to establish the initial values of the attributes of the object. In Plant, the constructor's parameters n and h receive the arguments, and the statements name = n; and height = h; store them in the new object's attributes. When the constructor finishes, the parameters disappear, but the attributes remain with the object for as long as it exists.
This is why the same class can produce objects with different starting states: each constructor call supplies its own arguments. A new Plant("fern", 30) and a new Plant("moss", 4) run the same constructor code with different values, giving two objects with different names and heights.
Arguments Are Evaluated First
Predict the output.
public class Plant
{
private String name;
private int height;
public Plant(String n, int h)
{
name = n;
height = h;
}
public void grow(int cm)
{
height = height + cm;
}
public String getName()
{
return name;
}
public int getHeight()
{
return height;
}
}
sunflower
20
- 1First argument.
kind + "flower"evaluates to "sunflower". - 2Second argument.
base + 5 * 2is 10 + 10 = 20 (multiplication first). - 3Then the constructor runs with the values "sunflower" and 20.
3Matching Arguments to Parameters
A constructor argument is a value that is passed into a constructor when the constructor is called. The arguments passed to a constructor must be compatible in order and number with the types identified in the parameter list in the constructor signature. For Plant(String n, int h), every call must supply a String and then an int.
Arguments can be any expressions of compatible types: literals, variables, arithmetic, or string concatenation. Java evaluates each one to a value before the constructor runs. An int argument may be passed to a double parameter through widening, but not the reverse, and the number of arguments must match the number of parameters exactly.
When a call does not match, the compiler's message points to the problem. A message such as "int cannot be converted to String" means an argument's type does not fit the parameter in that position, often because two arguments were swapped. A message about the constructor not being applicable to the given types usually means the number of arguments is wrong. In both cases, compare the call with the constructor's signature one position at a time.
| Call | Compiles? | Reason |
|---|---|---|
new Plant("fern", 30) | Yes | String, int matches Plant(String, int) |
new Plant("fern", 10 + 5) | Yes | The expression evaluates to an int first |
new Plant(30, "fern") | No | Wrong order |
new Plant("fern") | No | Too few arguments |
new Plant("fern", 30.5) | No | A double cannot be passed to the int parameter |
Arguments in the Wrong Order
Explain the compile error.
public class Plant
{
private String name;
private int height;
public Plant(String n, int h)
{
name = n;
height = h;
}
public void grow(int cm)
{
height = height + cm;
}
public String getName()
{
return name;
}
public int getHeight()
{
return height;
}
}
- 1The only constructor is
Plant(String, int). - 2The call supplies an
intthen aString, the reverse order. Java tries to pass 30 to theStringparameter and cannot. - 3Fix.
new Plant("fern", 30). Arguments must be compatible in order and number with the parameter list.
int cannot be converted to a String. The arguments must match the constructor's parameter types in order and number.new Plant("fern", 30.5) does not compile, because the second parameter is an int and a double cannot be narrowed automatically. Use an int value, or cast explicitly if truncation is acceptable.
4Arguments Are Passed by Value
When calling constructors, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments. If a variable is used as an argument, the constructor receives a copy of the variable's value, and later changes to the variable have no effect on the object.
This keeps objects independent of the variables used to create them. After new Plant("fern", start), the plant's height is whatever start held at the moment of the call. Reassigning start afterward changes the variable, not the plant. To change the plant's height, call one of its methods, such as grow.
Changing the Variable After the Call
Predict the output.
public class Plant
{
private String name;
private int height;
public Plant(String n, int h)
{
name = n;
height = h;
}
public void grow(int cm)
{
height = height + cm;
}
public String getName()
{
return name;
}
public int getHeight()
{
return height;
}
}
30
99
- 1The call copies 30 into the parameter
h, which is stored in the attributeheight. - 2
start = 99;changes only the variablestart. The object received a copy of the value, not the variable.
An object built from start does not stay connected to start. The constructor copied the value once. Changing start later has no effect on the object.
5Flow of Control During a Constructor Call
A constructor call interrupts the sequential execution of statements, causing the program to first execute the statements in the constructor before continuing. Once the last statement in the constructor has been executed, the flow of control is returned to the point immediately following where the constructor was called, and the new object's reference is stored in the variable.
This is the same pattern as a method call. When tracing, jump into the constructor at the new expression, run its statements in order, then return to finish the statement that contained the call. If the constructor prints anything, that output appears between the output of the statements before and after the object is created.
| Step | What happens | Output so far |
|---|---|---|
| 1 | main prints "before" | before |
| 2 | new Plant("ivy", 8): "ivy" and 8 copied into n and h | before |
| 3 | constructor prints start message, sets name and height, prints end message | before / starts / ends |
| 4 | reference stored in p; control returns to main | before / starts / ends |
| 5 | main prints "after: 8" | before / starts / ends / after: 8 |
Watching a Constructor Run
This version of the constructor prints messages. Predict the exact output order.
public class Plant
{
private String name;
private int height;
public Plant(String n, int h)
{
System.out.println(" constructor starts: " + n);
name = n;
height = h;
System.out.println(" constructor ends");
}
public int getHeight()
{
return height;
}
}
before
constructor starts: ivy
constructor ends
after: 8
- 1"before" prints first.
- 2The constructor call interrupts
main. Its statements run in order: the start message, the two assignments, the end message. - 3Control returns to the statement immediately after the call, which prints "after: 8".
6Creating Many Objects
Every evaluation of new creates exactly one new object. Three statements with new Plant(...) create three plants, each with its own attributes. Even when two constructor calls use identical arguments, they produce two separate objects that are not == to each other.
Library classes work the same way. A String can be created with a literal, as in "cedar", or by calling the String class constructor, as in new String("cedar"). The constructor form always creates a new object, which is why == reports false even when equals reports true.
Counting objects is a useful tracing skill. Scan the code for new: each evaluation creates one object, while assignments between variables, method calls, and declarations create none. A program with two new expressions and five variables still has only two objects, some of them referred to by more than one variable.
new creates one new object, and each object receives its own starting values from its constructor call.Constructing a String Explicitly
A String can be created with a literal or by calling the String constructor. Predict the output.
String a = new String("cedar");
String b = "cedar";
System.out.println(a.length());
System.out.println(a.equals(b));
System.out.println(a == b);
5
true
false
- 1
new String("cedar")calls theString(String)constructor and creates a new object with the same characters. - 2
equalscompares characters:true. - 3
==compares references.newalways creates a new object, soaandbare different objects:false.
new followed by a constructor call always creates a separate object, even when its contents match another.new Plant("mint", 9) written twice creates two different plants. Growing one does not grow the other, and == between them is false. Each new means one more object.
Four Habits for Creating Objects
1. new + Constructor
No object exists until new runs a constructor.
2. Arguments Set the Start
Parameters carry values into the new object's attributes.
3. Copies, Not Links
Call by value: later changes to variables do not affect the object.
4. Jump In, Then Return
The whole constructor runs before the next statement.
An object is typically created using the keyword new followed by a call to one of the class's constructors. Parameters allow constructors to accept values to establish the initial values of the attributes of the object. 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, and they are passed using call by value, which initializes the parameters with copies of the arguments. A constructor call interrupts sequential execution, runs the constructor's statements, and then returns control to the point immediately following the call.