AP Computer Science A · Study guide

Constructor Signatures

AP® Computer Science A · Using Objects and Methods

Constructor Signatures

What constructors are, how to read a constructor header and its signature, how a class can offer several overloaded constructors, and how Java decides which one runs for a given call.

Big Picture

A class contains constructors that are called to create objects. Constructors have the same name as the class, and their job is to give a brand-new object its starting attribute values. A constructor signature consists of the constructor's name, which is the same as the class name, and the ordered list of parameter types. When a class has several constructors with different signatures, the constructors are overloaded, and the arguments in each call determine which constructor runs.

1What Constructors Do

Every object starts life through a constructor. When a program writes new Ticket("Jazz Night", 12), Java creates a new Ticket object and runs a constructor that fills in its attributes: the event name, the row, and the price. Without a constructor, the object's attributes would have no meaningful starting values.

Constructors look much like methods, with a header and a body in braces, but they differ in three ways. A constructor's name is always exactly the class name. A constructor has no return type, not even void. And a constructor is not called on an existing object; it is called with the keyword new to create one. Recognizing these features lets you spot constructors immediately when reading a class or its documentation.

Many classes provide more than one way to build an object. A ticket might be created with just an event name, with an event and a row, or with an event and a custom price. Each option is a separate constructor, and each is identified by its signature.

Figure 1. Constructors look like methods, but they are named after the class, have no return type, and run only when an object is created with new.
TermMeaningExample
ConstructorCode in a class that is called to create an object; same name as the classpublic Ticket(String e, int r)
Parameter listThe types and names of the values a constructor receives(String e, int r)
Constructor signatureThe constructor's name and the ordered list of parameter typesTicket(String, int)
Overloaded constructorsSeveral constructors in one class with different signaturesTicket(), Ticket(String)

2Reading a Constructor Header

A constructor header has three parts. The access modifier, usually public, says that code in other classes may call it. Next comes the name, which matches the class name exactly, including capitalization. Finally, the parameter list in parentheses lists the types of the values that are passed and their variable names: (String e, int r) means the constructor receives a String called e and an int called r.

The parameter names are used inside the constructor's body to refer to the values passed in. A constructor with an empty parameter list, such as public Ticket(), receives no values and must choose all the starting attribute values itself; such a constructor typically sets sensible defaults.

Figure 2. A constructor has the same name as its class and no return type. Its signature is the class name and the ordered list of parameter types.
Worked Example 1 Reading headers

Finding Constructor Signatures

Give the signature of each constructor header from a class named Recipe.

  1. public Recipe()
  2. public Recipe(String title, int servings)
  3. public Recipe(String title, int servings, double minutes)
  4. public Recipe(int servings, String title)
  1. 11. Recipe(): an empty parameter list.
  2. 22. Recipe(String, int).
  3. 33. Recipe(String, int, double).
  4. 44. Recipe(int, String), which is different from 2 because the order of the types differs.
Result: The signatures are Recipe(), Recipe(String, int), Recipe(String, int, double), and Recipe(int, String). All four could exist in the same class because they are all different.
Common Mistake 1 · Giving a Constructor a Return Type

Writing public void Ticket() does not create a constructor. Because it has a return type, Java treats it as an ordinary method that happens to share the class name, and it will not run when an object is created. Constructors have no return type at all.

3Constructor Signatures

A constructor signature consists of the constructor's name, which is the same as the class name, and the ordered list of parameter types. The signature of public Ticket(String e, int r) is Ticket(String, int). Exactly as with method signatures, the parameter names and the access modifier are not part of it.

Order matters. Recipe(String, int) and Recipe(int, String) are different signatures, because the first parameter is a String in one and an int in the other. Two constructors whose headers differ only in parameter names, however, have the same signature and cannot both appear in the same class.

The reason is practical: a constructor call such as new Recipe("Soup", 4) supplies only values. Java must be able to decide from those values alone which constructor to run, so only the number, order, and types of the parameters can distinguish one constructor from another.

Pair of headersSame signature?Allowed together?
Ticket(String e) and Ticket(String name)YesNo
Ticket(String e, int r) and Ticket(int r, String e)No (order differs)Yes
Ticket(String e) and Ticket(String e, int r)No (count differs)Yes
Ticket(String e, int r) and Ticket(String e, double p)No (types differ)Yes
Worked Example 2 Illegal overloads

Constructors That Differ Only in Parameter Names

Why does this class not compile?

Code that does not compile
public class Badge
{
    private String label;

    public Badge(String name)
    {
        label = name;
    }

    public Badge(String title)
    {
        label = "Dr. " + title;
    }
}
  1. 1The signatures. Both constructors are Badge(String). Parameter names do not count.
  2. 2The problem. In a call such as new Badge("Reyes"), Java could not tell which constructor to run.
  3. 3Fix. Give the second constructor a different parameter list, such as Badge(String title, boolean doctor).
Result: The compiler reports that the constructor Badge(String) is already defined. Overloaded constructors must have different signatures.

4Overloaded Constructors

Constructors are said to be overloaded when there are multiple constructors with different signatures. Overloading gives users of a class flexible ways to create objects: Ticket offers a no-argument constructor for a general-admission ticket, one that takes an event name, one that adds a row, and one that adds a custom price.

Each overloaded constructor sets up a complete object, filling in every attribute. Values not supplied by the caller receive defaults chosen by the class's author. When reading a class, list its constructor signatures first; they tell you every way an object of that class can be created.

Figure 3. Constructors are overloaded when a class has multiple constructors with different signatures.
Worked Example 3 Which constructor runs?

Calling Overloaded Constructors

The Ticket class has the four constructors in Figure 3 and a describe method. Predict the output.

The Ticket class and a short program
public class Ticket
{
    private String event;
    private int row;
    private double price;

    public Ticket()
    {
        event = "General";
        row = 0;
        price = 20.0;
    }

    public Ticket(String e)
    {
        event = e;
        row = 0;
        price = 20.0;
    }

    public Ticket(String e, int r)
    {
        event = e;
        row = r;
        price = 35.0;
    }

    public Ticket(String e, double p)
    {
        event = e;
        row = 0;
        price = p;
    }

    public String describe()
    {
        return event + ", row " + row + ", " + price;
    }
}
Output
General, row 0, 20.0
Jazz Night, row 0, 20.0
Jazz Night, row 12, 35.0
Jazz Night, row 0, 12.5
  1. 1new Ticket(). No arguments: the no-parameter constructor sets "General", row 0, price 20.0.
  2. 2new Ticket("Jazz Night"). One String: Ticket(String).
  3. 3new Ticket("Jazz Night", 12). A String and an int: Ticket(String, int) sets row 12 and price 35.0.
  4. 4new Ticket("Jazz Night", 12.5). A String and a double: Ticket(String, double) sets the price to 12.5 and leaves row 0.
Result: The four lines show four different objects, each built by a different constructor. The arguments decide which constructor runs; note how 12 and 12.5 select different constructors.
Common Mistake 2 · Mixing Up the Order of Arguments

new Ticket(12, "Jazz Night") does not compile, even though Ticket(String, int) exists, because the arguments are in the wrong order. Match the arguments to the signature from left to right.

5Which Constructor Runs

When a constructor is called, Java compares the arguments with every constructor signature in the class and runs the one that matches in number, order, and type. If no signature matches, the call does not compile. When an exact match exists, it is chosen; automatic widening from int to double is used only when no exact match is available.

This means small details in a call matter. new Ticket("Expo", 3) and new Ticket("Expo", 3.0) look nearly identical but run different constructors and produce different objects. When predicting the result of constructor calls, write down the type of each argument before looking for the matching signature.

Figure 4. The constructor that runs is the one whose signature matches the arguments in the call.
CallArgument typesConstructor that runs
new Ticket()(none)Ticket()
new Ticket("Expo")StringTicket(String)
new Ticket("Expo", 3)String, intTicket(String, int)
new Ticket("Expo", 3.0)String, doubleTicket(String, double)
new Ticket(3, "Expo")int, StringNone: does not compile
Worked Example 4 Exact matches

int or double?

Both Ticket(String, int) and Ticket(String, double) could accept an int second argument, since an int can widen to a double. Which runs?

Using the same Ticket class
public class Ticket
{
    private String event;
    private int row;
    private double price;

    public Ticket()
    {
        event = "General";
        row = 0;
        price = 20.0;
    }

    public Ticket(String e)
    {
        event = e;
        row = 0;
        price = 20.0;
    }

    public Ticket(String e, int r)
    {
        event = e;
        row = r;
        price = 35.0;
    }

    public Ticket(String e, double p)
    {
        event = e;
        row = 0;
        price = p;
    }

    public String describe()
    {
        return event + ", row " + row + ", " + price;
    }
}
Output
Expo, row 3, 35.0
Expo, row 0, 3.0
  1. 1new Ticket("Expo", 3). The argument 3 is an int, and Ticket(String, int) matches exactly, so it runs: row 3, price 35.0.
  2. 2new Ticket("Expo", 3.0). 3.0 is a double, which cannot go to an int parameter, so Ticket(String, double) runs: price 3.0.
  3. 3The rule of thumb. When an exact match exists, it is chosen. Widening is used only when no exact match is available.
Result: The first ticket has row 3 and price 35.0; the second has row 0 and price 3.0. A single decimal point in an argument can change which constructor runs.
Worked Example 5 No match

A Call That Matches No Constructor

Explain the compile error.

Code that does not compile
public class Ticket
{
    private String event;
    private int row;
    private double price;

    public Ticket()
    {
        event = "General";
        row = 0;
        price = 20.0;
    }

    public Ticket(String e)
    {
        event = e;
        row = 0;
        price = 20.0;
    }

    public Ticket(String e, int r)
    {
        event = e;
        row = r;
        price = 35.0;
    }

    public Ticket(String e, double p)
    {
        event = e;
        row = 0;
        price = p;
    }

    public String describe()
    {
        return event + ", row " + row + ", " + price;
    }
}
  1. 1The arguments. An int followed by a String.
  2. 2The signatures available. Ticket(), Ticket(String), Ticket(String, int), and Ticket(String, double). None has an int first.
  3. 3Fix. Pass the arguments in the order the signature expects: new Ticket("Jazz Night", 12).
Result: The compiler reports that no suitable constructor was found. The arguments of a constructor call must match one signature in number, order, and type.
Common Mistake 3 · Ignoring the Type of a Literal

3 is an int literal and 3.0 is a double literal. With overloaded constructors, that difference decides which constructor runs. Always identify the type of every argument, including literals, before matching a signature.

6Constructors and Documentation

The documentation for a class lists its constructors along with a description of each. As with methods, procedural abstraction applies: to create an object correctly, you need the constructor's signature and a description of what it does, not the code inside it. Reading the list of constructors tells you every way the class lets you create an object and which information you must supply.

When several constructors could meet a need, choose the one whose description matches the situation most directly, and supply the arguments in exactly the order the signature gives. Good documentation also states any requirements, such as "width must be positive," which are preconditions the caller is responsible for meeting.

Worked Example 6 Using documentation

Choosing a Constructor From a List

A class Garden documents these constructors:

  • Garden(int width, int length): a garden of the given size with no plants
  • Garden(int width, int length, String crop): a garden of the given size planted with one crop
  • Garden(int side): a square garden with no plants

Write a call for: (1) an empty 6 by 9 garden; (2) a 4 by 4 square garden with no plants; (3) a 3 by 10 garden of beans.

  1. 1(1) Two int arguments: new Garden(6, 9).
  2. 2(2) Either new Garden(4) or new Garden(4, 4) works; the one-parameter constructor exists exactly for squares.
  3. 3(3) Two int values then a String: new Garden(3, 10, "beans").
Result: Reading the signatures and descriptions is enough to choose correctly: new Garden(6, 9), new Garden(4), and new Garden(3, 10, "beans").
Common Mistake 4 · Confusing a Constructor With a Method

A constructor is called once, with new, to create an object. Methods are called on objects that already exist, using the dot operator. ticket.Ticket("Expo") is not valid; to create a new ticket, write new Ticket("Expo").

Four Habits for Constructors

1. Name = Class Name

No return type; called with new.

2. Signature = Name + Types

Ordered parameter types; names never count.

3. Type Each Argument

3 and 3.0 can select different constructors.

4. Read the List First

The constructor signatures show every way to build an object.

Core Synthesis

A class contains constructors that are called to create objects, and they have the same name as the class. A constructor signature consists of the constructor's name, which is the same as the class name, and the ordered list of parameter types; the parameter list in the header lists the types of the values that are passed and their variable names. Constructors are overloaded when there are multiple constructors with different signatures, and the arguments in a call determine which one runs.