AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/1/1-13)
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 signatureBook(String, String, int).Book(String title), with signatureBook(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.
- Example 1
Which constructor runs?
Using the
Bookclass described above, what does the first code block print, and what areb2's pages andb3's value?Show the solutionHide the solution
- Step 1:
b1: three arguments,String,String,int, matchBook(String, String, int). Its author is Herbert. - Step 2:
b2: oneStringargument matchesBook(String), which sets the author to "unknown" and the pages to 0. - Step 3:
b3is assignednull, so no object is created andb3refers to nothing. - Step 4: The print joins
b1.getAuthor(), a space andb2.getAuthor().
Answer: It prints
Herbert unknown.b2has 0 pages, andb3isnull. - Step 1:
- Example 2
When does the constructor run?
The
Loudclass's constructor printsbuildingand setslevelto twice its parameter;getLevel()returnslevel. What does this code print?System.out.println("before"); Loud thing = new Loud(3); System.out.println("after " + thing.getLevel());Show the solutionHide the solution
- Step 1: Line 1 prints
before. - Step 2: Line 2 calls the constructor. Control jumps into it, it prints
building, and it stores 3 × 2 = 6 inlevel. Then control returns, and the reference to the new object is stored inthing. - Step 3: Line 3 prints
afterfollowed bything.getLevel(), which is 6.
Answer: Three lines:
before,building,after 6. - Step 1: Line 1 prints
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
nullholds 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
Check yourself
5 questions on 1.13 Object Creation and Storage (Instantiation). Pick an answer to see if you got it, and why.
A programmer writes Lamp desk = null;. Which of the following best describes desk after this statement?
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();
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;
}
}Which of the following statements, appearing in a class other than Book, compiles without error?
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());
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