Skip to main content

Unit 1 · Topic 1.13

1.13 Object Creation and Storage (Instantiation)

Creating an object means calling a constructor with new. This topic covers how to read a constructor's signature, how Java chooses between overloaded constructors, and what a reference variable holds before and after an object is created.

Key terms

  • constructor
  • new
  • instantiation
  • constructor signature
  • overloaded constructors
  • null

Constructors

A constructor is a special block of code in a class that runs when a new object is created. Its job is to set up the object's starting values. A constructor always has exactly the same name as its class, and it has no return type.

You create an object with the keyword new followed by a constructor call. The expression gives back a reference to the new object, which you usually store in a variable:

Book b1 = new Book("Dune", "Herbert", 412); Book b2 = new Book("Dune"); Book b3 = null; System.out.println(b1.getAuthor() + " " + b2.getAuthor());

Constructor signatures and overloading

A constructor's signature is the class name plus the ordered list of its parameter types. The Book class used above has two constructors:

  • Book(String title, String author, int pages), with signature Book(String, String, int).
  • Book(String title), with signature Book(String). It sets the author to "unknown" and the pages to 0.

Matching arguments to parameters

Having more than one constructor with different signatures is called overloading. Java chooses the constructor whose parameter list matches the arguments in number, order and type. The arguments are passed by value, so each parameter starts as a copy of its argument, and the constructor uses those values to set the new object's attributes.

If no constructor matches, the code doesn't compile. Both of these fail with the Book class above:

Book b4 = new Book("Dune", 412);

Book b5 = new Book(412, "Dune", "Herbert");

The first has two arguments, and no constructor takes a String and an int. The second has the right number of arguments but in the wrong order.

null and the flow of control

A reference variable that doesn't refer to any object holds null. In the first code block, b3 is a valid Book variable, but no Book object exists for it yet.

Strings are objects too. You can make one with a literal, "hi", or by calling the String constructor, new String("hi"). Both hold the same characters.

Like a method call, a constructor call interrupts the code that's running. Java runs the constructor's statements, then returns to the statement where new was used. If a constructor prints something, that output appears at the moment the object is created.

Worked examples

Try each one yourself first, then open the solution.

  1. Example 1

    Which constructor runs?

    Using the Book class described above, what does the first code block print, and what are b2's pages and b3's value?

    Show the solution
    1. Step 1: b1: three arguments, String, String, int, match Book(String, String, int). Its author is Herbert.
    2. Step 2: b2: one String argument matches Book(String), which sets the author to "unknown" and the pages to 0.
    3. Step 3: b3 is assigned null, so no object is created and b3 refers to nothing.
    4. Step 4: The print joins b1.getAuthor(), a space and b2.getAuthor().

    Answer: It prints Herbert unknown. b2 has 0 pages, and b3 is null.

  2. Example 2

    When does the constructor run?

    The Loud class's constructor prints building and sets level to twice its parameter; getLevel() returns level. What does this code print?System.out.println("before"); Loud thing = new Loud(3); System.out.println("after " + thing.getLevel());

    Show the solution
    1. Step 1: Line 1 prints before.
    2. Step 2: Line 2 calls the constructor. Control jumps into it, it prints building, and it stores 3 × 2 = 6 in level. Then control returns, and the reference to the new object is stored in thing.
    3. Step 3: Line 3 prints after followed by thing.getLevel(), which is 6.

    Answer: Three lines: before, building, after 6.

Common mistakes

  • Passing arguments in a different order from the constructor's parameter list. Types must line up position by position.
  • Forgetting new. Book b = Book("Dune"); doesn't compile.
  • Thinking a variable set to null holds an empty object. It holds no object at all.
  • Giving a constructor a return type such as void. Constructors have none.

On the exam

  • Expect "which of these creates an object correctly?" questions. For each choice, find a constructor signature that matches the argument types in order.
  • On the Class Design free-response question, you'll write a constructor yourself (3.4), so it helps to read constructor signatures fluently now.

Connected topics

Videos

  • AP Computer Science A - Topic 1.13: Object Creation and Storage

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • Object Creation and Storage Instantiation (Part 1)

    CodeHSWatch on YouTube (opens in a new tab)

  • What is null and a null pointer exception? (Java Tutorial)

    Bill BarnumWatch on YouTube (opens in a new tab)

  • Object Creation and Storage Instantiation (Part 2)

    CodeHSWatch on YouTube (opens in a new tab)

  • AP CS A Unit 2 Lesson 2 - Creating and Storing Objects (Instantiation)

    Jacob MacMillanWatch on YouTube (opens in a new tab)

Check yourself

5 questions on 1.13 Object Creation and Storage (Instantiation). Pick an answer to see if you got it, and why.

Question 1 of 5

A programmer writes Lamp desk = null;. Which of the following best describes desk after this statement?

Question 2 of 5

Consider the following class.public class Lamp { private int level; public Lamp() { level = 1; System.out.print("A"); } public Lamp(int start) { level = start; System.out.print("B"); } public void brighten() { level++; System.out.print(level); } }What is printed as a result of executing the following code segment?Lamp x = new Lamp(5); Lamp y = new Lamp(); y.brighten(); x.brighten();

Code
public class Book
{
    private String title;
    private int pages;
 
    public Book(String t)
    {
        title = t;
        pages = 100;
    }
 
    public Book(String t, int p)
    {
        title = t;
        pages = p;
    }
 
    public int getPages()
    {
        return pages;
    }
 
    public void addPages(int extra)
    {
        pages += extra;
    }
}
Question 3 of 5

Which of the following statements, appearing in a class other than Book, compiles without error?

Question 4 of 5

What is printed by the following code segment?Book a = new Book("Emma"); Book b = new Book("Persuasion", 250); a.addPages(20); System.out.println(a.getPages() + b.getPages());

Question 5 of 5

What is printed by the following code segment?Book first = new Book("Ivanhoe", 300); Book second = first; second.addPages(50); System.out.println(first.getPages());

0 of 5 answered