AP · Computer Science A · Anatomy of a Class

Writing Constructors

14 min readUpdated December 1, 2026FreeAP Computer Science A, Class Creation

A constructor runs when new creates an object: it has the class's name and no return type, and it gives each instance variable a starting value, usually from its parameters. An instance variable it leaves alone keeps its default value: 0, 0.0, false or null. A class can have several constructors with different parameter lists, and a parameter named like an instance variable hides it unless you write this..

Quick check

  1. In a class, what does private int score; declare, and which code can use score directly?Show answerHide answer

    An instance variable: every object of the class gets its own score. Because it is private, only code inside the class can use it directly.

  2. In Dog d = new Dog();, what does the variable d hold?Show answerHide answer

    A reference to the new Dog object that new created.

  3. A class has private boolean done; and its constructor never mentions done. What does done hold in a new object?Show answerHide answer

    false, the default value for a boolean instance variable.

Know these already? Jump to the practice questions

What you'll be able to do

  • State the rules for a constructor header.
  • Determine a new object's state by tracing its constructor.
  • State the default value of an unset instance variable.
  • Identify which overloaded constructor a new call runs.
  • Explain why name = name; leaves an instance variable unset.

Key terms

Constructor

Code with the class's name and no return type that runs once each time new creates an object, setting its initial state.

In plain English
The setup code for a new object.
Don't write
"A constructor returns void."

Default value

The value an instance variable holds if it is never assigned: 0, 0.0, false or null, by type.

In plain English
What an instance variable holds if nobody sets it.
Don't write
"An unset instance variable holds a random value."

Shadowing

A parameter with the same name as an instance variable hides it, so the plain name means the parameter.

In plain English
The nearer variable wins the name.
Don't write
"name = name; copies the parameter into the instance variable."

What does a constructor do?

A constructor runs once, when new creates an object. Its header looks like a method header except that its name is exactly the class name and it has no return type, not even void. Constructors are usually public, so code outside the class can create objects.

public class Lamp
{
    private int watts;
    private boolean on;

    public Lamp(int w, boolean o)
    {
        watts = w;
        on = o;
    }
}

new Lamp(40, true) passes the arguments 40 and true into the parameters w and o, so watts becomes 40 and on becomes true. Parameters disappear when the constructor ends, but instance variables last as long as the object, which is why the constructor copies each parameter into one.

Key idea

A constructor's job is to copy or compute a starting value for each instance variable.

Check yourself

Why does public void Lamp(int w, boolean o) not work as a constructor?
Show answerHide answer

Adding void gives it a return type, so it is an ordinary method that shares the class's name; new Lamp(40, true) cannot use it.

What does an instance variable hold if the constructor skips it?

Before the constructor body runs, every instance variable already holds its default value. Learn this: the defaults are not on the Java Quick Reference.

TypeDefault value
int0
double0.0
booleanfalse
String or any other referencenull

The body replaces the values it assigns; anything it never mentions keeps its default. If a class has no constructor at all, Java supplies a no-argument one, and every instance variable without an initial value in its declaration holds its default.

Defaults apply to instance and static variables, but never to local variables. A local variable gets no default, and using it before you assign it is a compile-time error.

Check yourself

A class has private String name; and private int age;, and its only constructor sets age. What does name hold in a new object?
Show answerHide answer

null, the default value for a reference.

How does Java choose between overloaded constructors?

Overloaded constructors are constructors in one class with different parameter lists. Java runs the one whose parameter list fits the arguments: their number, types and order.

public Lamp()
{
    watts = 60;
}

Added to Lamp, this gives two constructors. new Lamp() runs this one: watts becomes 60 and on keeps its default, false. new Lamp(40, true) runs the two-parameter one.

Two constructors with the same parameter types in the same order cause a compile-time error; parameter names don't count. Once you write any constructor, Java stops supplying the automatic no-argument one, so new Lamp() compiles only if you write Lamp() yourself.

Check yourself

A class has constructors Pen(String c) and Pen(String c, int s). Which one does new Pen("red", 3) run?
Show answerHide answer

Pen(String c, int s): there are two arguments, a String then an int.

Why doesn't name = name; set the instance variable?

Inside a constructor, a parameter shadows an instance variable with the same name. In name = name; both sides mean the parameter, so the line copies the parameter into itself. It compiles, but the instance variable keeps its default, null.

Two fixes work:

  • Write this.name = name;. this.name means the current object's instance variable, and the plain name means the parameter.
  • Give the parameter a different name, such as n, and write name = n;.

The note on scope, access and the this keyword covers this in full.

Check yourself

The parameter is called price and so is an instance variable. Which side of this.price = price; is the instance variable?
Show answerHide answer

The left side, this.price.

Worked example 1: Trace a constructor

Question: What is printed when this code runs?

public class Ticket
{
    private String event;
    private int row;
    private double price;
    private boolean scanned;

    public Ticket(String e, int r)
    {
        event = e;
        row = r;
        price = 40.0 - 2 * r;
    }

    public String getInfo()
    {
        return event + " row " + row + " " + price + " " + scanned;
    }
}
Ticket t = new Ticket("Jazz", 7);
System.out.println(t.getInfo());

What tells you the method

A new call then a method that reads the state, so trace the instance variables.

  1. Step 1: Trace the body with e = "Jazz" and r = 7, starting from the defaults.

    Aftereventrowpricescanned
    defaultsnull00.0false
    event = e;"Jazz"00.0false
    row = r;"Jazz"70.0false
    price = 40.0 - 2 * r;"Jazz"726.0false
    Why

    Defaults are in place before the body runs. 2 * r is 14, and 40.0 − 14 is the double 26.0. Nothing sets scanned.

  2. Step 2: Build the string.

    getInfo joins the values in order.

    Why

    A double prints with a decimal point, and a boolean as false.

Check it

With r = 0 the price would be 40.0, the top price, so 26.0 for row 7 is sensible.

Answer

Jazz row 7 26.0 false

Worked example 2: Design an overloaded constructor

Question: Design a second constructor for this class so that new Timer(135) makes a timer of 2 minutes 15 seconds. Then state what System.out.println(new Timer(135).getTime()); prints.

public class Timer
{
    private int minutes;
    private int seconds;

    public Timer(int m, int s)
    {
        minutes = m;
        seconds = s;
    }

    public String getTime()
    {
        return minutes + ":" + seconds;
    }
}

What tells you the method

A design task: plan, write the header, then trace.

  1. Step 1: State the input, the output and the plan.

    The input is a number of seconds; the output is both instance variables set. Minutes are total / 60; the seconds left over are total % 60.

    Why

    int division drops the remainder, and % gives exactly that remainder.

  2. Step 2: Write the header and body.

    public Timer(int total)
    {
        minutes = total / 60;
        seconds = total % 60;
    }
    
    Why

    One int parameter differs from the existing two-parameter list, so the overload is legal.

  3. Step 3: Trace it on 135.

    135 / 60 is 2 and 135 % 60 is 15, so getTime() returns "2:15".

    Why

    Tracing on a stated input tests the design.

Check it

On 59 the values are 0 and 59; on 60, the boundary, they are 1 and 0.

Answer

2:15

Worked example 3: Fix a shadowed parameter

Question: The statements Book b = new Book("Dune", 412); and System.out.println(b.getTitle()); print null. Which change makes them print Dune?

1: public class Book
2: {
3:     private String title;
4:     private int pages;
5:
6:     public Book(String title, int p)
7:     {
8:         title = title;
9:         pages = p;
10:    }
11:
12:    public String getTitle()
13:    {
14:        return title;
15:    }
16: }
  • A) Change line 8 to this.title = title;
  • B) Change line 8 to title = this.title;
  • C) Change line 6 to public void Book(String title, int p)
  • D) Change line 14 to return this.title;

What tells you the method

A parameter has the same name as an instance variable, so check which variable each title means.

  1. Step 1: Find the fault.

    In line 8 both titles are the parameter, so the instance variable stays null.

    Why

    The parameter shadows the instance variable inside the constructor.

  2. Step 2: Test each option.

    A stores "Dune" in the instance variable. B copies null into the parameter. C makes the constructor a method, so new Book("Dune", 412) no longer compiles. D reads the instance variable, which is still null.

    Why

    Only assigning to this.title sets the object's state.

Check it

With A, getTitle() returns the instance variable, now "Dune".

Answer

A

Your turn

Question: What is printed when this code runs?

public class Badge
{
    private String name;
    private int level;

    public Badge(String n)
    {
        name = n;
        level = 1;
    }

    public Badge(String n, int lv)
    {
        name = n;
        level = lv;
    }

    public String show()
    {
        return name + level;
    }
}
Badge a = new Badge("Kai");
Badge b = new Badge("Ana", 4);
System.out.println(a.show() + " " + b.show());
  1. Step 1: Match the first call.

    new Badge("Kai") has one String argument, so it runs Badge(String n): name is "Kai" and level is 1.

  2. Step 2: Your go: match the second call, then build the printed line.

Show the full solutionHide the solution

Step 2. new Badge("Ana", 4) has a String then an int, so it runs Badge(String n, int lv): name is "Ana" and level is 4. a.show() is "Kai1" and b.show() is "Ana4", joined by a space.

Answer: Kai1 Ana4

Traps

Trap

Every variable starts at 0 or null if you don't set it.

It seems right because instance variables do. But local variables get no default, so reading one before assigning it is a compile-time error.

Inside a constructor, does int total; total = total + 5; compile?

No: total is a local variable with no value yet.

Trap

Writing a constructor with parameters keeps the automatic no-argument one.

It seems right because a class with no constructor allows new Ticket(). But Java supplies that constructor only when a class declares none, so after you write Ticket(String e, int r), new Ticket() fails to compile.

Class Cup has only Cup(int size). Does new Cup() compile?

No: Cup has no no-argument constructor.

What's examined

On the AP® Computer Science A exam (Unit 3: Class Creation), multiple-choice questions ask which constructor a call runs, what state a new object has, or which code completes a constructor. The class design free-response question has you write a class, constructor included, so make sure the constructor sets every instance variable.

Practice questions

  1. Recall Which is a valid constructor header for a class named Robot?
  • A) public void Robot(int id)
  • B) public Robot(int id)
  • C) public robot(int id)
  • D) public Robot Robot(int id)
Show answer

Answer: B. A constructor has exactly the class name and no return type.

Why the others are wrong:

  • A has the return type void, so it is a method.
  • C misspells the class name: Java is case-sensitive, so robot is not Robot.
  • D has the return type Robot, so it is a method.
  1. Recall Name the default value of a String instance variable that no constructor sets.
Show answer

Answer: null

Marking points:

  • A String variable holds a reference, and an unset reference instance variable is null.
  1. Apply What is printed?
public class Lamp
{
    private int watts;
    private boolean on;

    public Lamp()
    {
        watts = 60;
    }

    public Lamp(int w, boolean o)
    {
        watts = w;
        on = o;
    }

    public String status()
    {
        return watts + " " + on;
    }
}
Lamp x = new Lamp();
Lamp y = new Lamp(40, true);
System.out.println(x.status());
System.out.println(y.status());
Show answer

Answer: 60 false then 40 true on the next line.

Marking points:

  • Lamp() sets watts to 60; on keeps its default, false.
  • Lamp(40, true) sets both instance variables from the arguments.
  1. Exam-style The constructor should set both instance variables from its parameters. Give the number of the line that stops it working.
1: public class Crate
2: {
3:     private int width;
4:     private int depth;
5:
6:     public Crate(int w, int d)
7:     {
8:         width = w;
9:         d = depth;
10:    }
11: }
Show answer

Answer: Line 9.

Marking points:

  • Line 9 copies the instance variable (still 0) into the parameter, the wrong way round.
  • The fix is depth = d;; after new Crate(3, 5), depth would then be 5.
  1. Exam-style A class Song has exactly two constructors: Song(String t) and Song(String t, int s). Which statement causes a compile-time error?
  • A) Song a = new Song("Echo");
  • B) Song b = new Song("Echo", 200);
  • C) Song c = new Song();
  • D) Song d = new Song("Echo", 3 / 2);
Show answer

Answer: C. The class declares constructors, so Java supplies no no-argument one, and none was written.

Why the others are wrong:

  • A matches Song(String t).
  • B matches Song(String t, int s).
  • D also matches it: 3 / 2 is int division, giving the int 1, not 1.5.
  1. Exam-style What is printed?
public class Recipe
{
    private String dish;
    private int servings;
    private double cups;
    private int extra;

    public Recipe(String d, int people)
    {
        dish = d;
        servings = people / 4;
        cups = people / 4.0;
    }

    public String summary()
    {
        return dish + ": " + servings + ", " + cups + ", " + extra;
    }
}
Recipe r = new Recipe("soup", 10);
System.out.println(r.summary());
Show answer

Answer: soup: 2, 2.5, 0

Marking points:

  • 10 / 4 is int division, so servings is 2.
  • 10 / 4.0 is double division, so cups is 2.5.
  • Nothing sets extra, so it keeps its default, 0.
  1. Exam-style A class has private String owner; and private double balance;. Its constructor header is public Account(String owner, double start). Which code segment completes the constructor so both instance variables are set from the parameters?
  • A) owner = owner; then balance = start;
  • B) this.owner = owner; then start = balance;
  • C) this.owner = owner; then this.balance = balance;
  • D) this.owner = owner; then balance = start;
Show answer

Answer: D. this.owner is the instance variable, and balance has no parameter shadowing it.

Why the others are wrong:

  • A assigns the parameter owner to itself, so the instance variable stays null.
  • B copies the instance variable into the parameter, the wrong way round.
  • C uses the instance variable's name where the parameter start belongs, so balance is assigned to itself and stays 0.0.
  1. Apply How many times does a constructor run when this code executes?
Lamp a = new Lamp();
Lamp b = a;
Lamp c = new Lamp(25, false);
Show answer

Answer: 2

Marking points:

  • A constructor runs once for each new, and there are two.
  • Lamp b = a; copies a reference; it creates no object.

Key points

Recall, then reveal

Say the main points from memory first, then check them.

Show key pointsHide key points
  • A constructor has the class's name and no return type, and runs once per new.
  • Unset instance variables hold 0, 0.0, false or null; local variables get no default.
  • Java picks the overloaded constructor whose parameter list matches the arguments.
  • Writing any constructor removes the automatic no-argument one.
  • When a parameter shares an instance variable's name, assign with this.name = name;.

Keep learning

Explore AP Computer Science A tutoring →

View the full Computer Science A syllabus →

More in this unit

Class Creation

All Anatomy of a Class notes

Part of Novark's AP Computer Science A notes