AP Computer Science A · Study guide

Object Instantiation

AP® Computer Science A · Using Objects and Methods

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.

Big Picture

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.

Figure 1. An object is typically created using the keyword new followed by a call to one of the class's constructors.
PartExampleRole
Declared type and namePlant fernCreates a reference variable
newnewCreates a new object
Constructor callPlant("fern", 30)Sets the new object's starting attributes
Assignment=Stores the reference to the new object in the variable
Worked Example 1 Creating and using objects

Building Plants and Reading Their State

The class Plant is given. Predict the output.

The Plant class and a short program
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;
    }
}
Output
fern 35
moss 4
  1. 1Two constructor calls. fern starts with name "fern" and height 30; moss with "moss" and 4.
  2. 2fern.grow(5) raises only fern's height, to 35.
  3. 3Reading state. The getter methods return each object's current values.
Result: The output is fern 35 and moss 4. The constructor arguments set each object's starting attributes; later method calls change them.
Worked Example 2 Declare, then create

Creating an Object Later and Replacing It

Predict the output.

Using the same Plant class
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;
    }
}
Output
sage 10
dill 3
  1. 1Plant p; declares the variable; no object exists yet.
  2. 2p = new Plant("sage", 6); creates the first plant; grow(4) raises its height to 10.
  3. 3p = new Plant("dill", 3); creates a second, separate plant with its own starting values and stores its reference in p. The sage plant is not changed; p simply refers to a different object now.
Result: The output is sage 10, then dill 3. Declaring a variable and creating an object can be separate steps, and each new builds a fresh object with values from its own constructor call.
Common Mistake 1 · Forgetting new

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.

Figure 2. Parameters allow constructors to accept values to establish the initial values of the attributes of the object.
Worked Example 3 Expressions as arguments

Arguments Are Evaluated First

Predict the output.

Using the same Plant class
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;
    }
}
Output
sunflower
20
  1. 1First argument. kind + "flower" evaluates to "sunflower".
  2. 2Second argument. base + 5 * 2 is 10 + 10 = 20 (multiplication first).
  3. 3Then the constructor runs with the values "sunflower" and 20.
Result: The output is sunflower and 20. Each argument expression is evaluated to a value before the constructor receives it.

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.

CallCompiles?Reason
new Plant("fern", 30)YesString, int matches Plant(String, int)
new Plant("fern", 10 + 5)YesThe expression evaluates to an int first
new Plant(30, "fern")NoWrong order
new Plant("fern")NoToo few arguments
new Plant("fern", 30.5)NoA double cannot be passed to the int parameter
Worked Example 4 Compatibility

Arguments in the Wrong Order

Explain the compile error.

Code that does not compile
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;
    }
}
  1. 1The only constructor is Plant(String, int).
  2. 2The call supplies an int then a String, the reverse order. Java tries to pass 30 to the String parameter and cannot.
  3. 3Fix. new Plant("fern", 30). Arguments must be compatible in order and number with the parameter list.
Result: The compiler reports incompatible types: an int cannot be converted to a String. The arguments must match the constructor's parameter types in order and number.
Common Mistake 2 · Passing a double Where an int Is Expected

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.

Worked Example 5 Call by value

Changing the Variable After the Call

Predict the output.

Using the same Plant class
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;
    }
}
Output
30
99
  1. 1The call copies 30 into the parameter h, which is stored in the attribute height.
  2. 2start = 99; changes only the variable start. The object received a copy of the value, not the variable.
Result: The output is 30 and 99. Constructor arguments are passed using call by value, which initializes the parameters with copies of the arguments.
Common Mistake 3 · Expecting an Object to Track a 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.

Figure 3. A constructor call interrupts the sequential execution of statements. Once the last statement in the constructor runs, control returns to the point immediately following the call.
StepWhat happensOutput so far
1main prints "before"before
2new Plant("ivy", 8): "ivy" and 8 copied into n and hbefore
3constructor prints start message, sets name and height, prints end messagebefore / starts / ends
4reference stored in p; control returns to mainbefore / starts / ends
5main prints "after: 8"before / starts / ends / after: 8
Worked Example 6 Flow of control

Watching a Constructor Run

This version of the constructor prints messages. Predict the exact output order.

A Plant constructor that prints
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;
    }
}
Output
before
  constructor starts: ivy
  constructor ends
after: 8
  1. 1"before" prints first.
  2. 2The constructor call interrupts main. Its statements run in order: the start message, the two assignments, the end message.
  3. 3Control returns to the statement immediately after the call, which prints "after: 8".
Result: The output has four lines: before, the two constructor messages, and after: 8. A constructor call runs the whole constructor before the next statement continues.

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.

Figure 4. Every evaluation of new creates one new object, and each object receives its own starting values from its constructor call.
Worked Example 7 Library objects

Constructing a String Explicitly

A String can be created with a literal or by calling the String constructor. Predict the output.

Code
String a = new String("cedar");
String b = "cedar";
System.out.println(a.length());
System.out.println(a.equals(b));
System.out.println(a == b);
Output
5
true
false
  1. 1new String("cedar") calls the String(String) constructor and creates a new object with the same characters.
  2. 2equals compares characters: true.
  3. 3== compares references. new always creates a new object, so a and b are different objects: false.
Result: The output is 5, true, and false. new followed by a constructor call always creates a separate object, even when its contents match another.
Common Mistake 4 · Assuming Identical Arguments Give the Same Object

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.

Core Synthesis

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.