PrepGo

Constructors - AP Computer Science A Study Guide

Written by AP Content Team, Verified for 2026 AP Exams, Last updated: May 2026

Learn with study guides reviewed by top AP teachers. This guide takes about 10 minutes to read.

Getting Started

In object-oriented programming, a class acts as a blueprint for creating objects. But how do we ensure that each object is set up correctly the moment it is created? Constructors solve this problem by providing a dedicated mechanism to initialize an object's state, ensuring every new instance starts its life in a valid and predictable condition.

What You Should Be Able to Do

  • Define one or more constructors within a class to initialize instance variables.

  • Write code that creates new objects by calling a constructor with the new keyword.

  • Implement overloaded constructors to provide multiple ways of creating an object.

  • Explain the role and behavior of the default no-argument constructor.

  • Trace the flow of execution when an object is created and its constructor is called.

Key Concepts & Java Implementation

The Core Idea

A constructor is a special block of code that is executed when a new object is created. Its primary purpose is to initialize the instance variables—the variables that define an object's state. Think of it as the setup routine for an object. When you use the new keyword to create an instance of a class, you are not just allocating memory; you are also calling a constructor to populate that memory with meaningful starting values.

Without a constructor, instance variables are given default values (e.g., 0 for numeric types, false for boolean, and null for object references). This can lead to objects existing in an incomplete or invalid state. Constructors enforce a contract, guaranteeing that an object is properly configured from the moment of its creation. For example, a Student object can be constructed with a name and ID, ensuring no Student can exist without these essential attributes.

Syntax & Implementation

Constructors are defined inside a class. They look similar to methods but have two strict rules:

  1. The constructor name must be exactly the same as the class name.

  2. A constructor has no return type, not even void.

You can define multiple constructors in the same class, as long as their parameter lists are different. This is known as constructor overloading.

  • Syntax Table
ComponentPurposeJava Example
public ClassName(...)The constructor declaration. It must match the class name and have no return type.public Book(...)
(parameters)A list of values passed in to initialize the object's state. Can be empty.(String title, String author)
newThe keyword used to create a new object instance and invoke its constructor.new Book("Moby Dick", "Herman Melville")
  • Annotated Java Examples

Here is a Rectangle class with two instance variables. We will add constructors to initialize them.

1. A Constructor with Parameters

This is the most common type of constructor. It accepts arguments to set the initial state of the object.


public class Rectangle {

    private int width;

    private int height;


    // Constructor with two parameters

    public Rectangle(int initialWidth, int initialHeight) {

        // 'this.width' refers to the instance variable.

        // 'initialWidth' refers to the parameter.

        this.width = initialWidth;

        this.height = initialHeight;

    }


    // A method to get the area

    public int getArea() {

        return this.width * this.height;

    }

}

To use this constructor, we call it with the new keyword in another class:


public class Geometry {

    public static void main(String[] args) {

        // Create a Rectangle object by calling the constructor.

        // The arguments 10 and 25 are passed to the constructor's parameters.

        Rectangle rect1 = new Rectangle(10, 25);


        System.out.println("The area is: " + rect1.getArea()); // Prints: The area is: 250

    }

}

2. Overloaded Constructors

A class can have multiple constructors. This provides flexibility in how objects are created. Here, we add a no-argument constructor to create a default 1x1 square.


public class Rectangle {

    private int width;

    private int height;


    // Constructor 1: Takes width and height

    public Rectangle(int initialWidth, int initialHeight) {

        this.width = initialWidth;

        this.height = initialHeight;

    }


    // Constructor 2: A no-argument constructor for a default square

    public Rectangle() {

        // If no arguments are provided, create a 1x1 square.

        this.width = 1;

        this.height = 1;

    }


    public int getArea() {

        return this.width * this.height;

    }

}

Now we can create Rectangle objects in two different ways:


// In a main method...

Rectangle rect1 = new Rectangle(10, 25); // Uses the first constructor

Rectangle rect2 = new Rectangle();       // Uses the no-argument constructor

Tracing & Analysis

  • Execution Trace

Let's trace the line: Rectangle rect1 = new Rectangle(10, 25);

  1. new Rectangle(...): Java allocates a new block of memory large enough to hold a Rectangle object (with space for an intwidth and an intheight).

  2. Constructor Call: The Rectangle constructor that matches the signature (int, int) is invoked. The value 10 is passed to the initialWidth parameter, and 25 is passed to initialHeight.

  3. Initialization: Inside the constructor, the code executes:

    • this.width = initialWidth; assigns the value of initialWidth (10) to the new object's width instance variable.

    • this.height = initialHeight; assigns the value of initialHeight (25) to the new object's height instance variable.

  4. Return: The constructor completes. The new operator returns a reference (the memory address) to the newly created and initialized object.

  5. Assignment: This reference is stored in the variable rect1. The variable rect1 now points to the Rectangle object in memory whose width is 10 and height is 25.

  • Analysis

Constructors are fundamental to encapsulation. By defining how an object must be created, a class designer prevents users of the class from creating objects in an invalid state. For example, by only providing a constructor that requires a positive width and height, you can enforce that no Rectangle object can ever be created with zero or negative dimensions.

Java Syntax Quick-Reference

  • new ClassName(arguments): The operator and call used to create a new object. It allocates memory for the object and invokes the matching constructor to initialize it.

  • public ClassName(parameters) { ... }: The syntax for defining a constructor. The name must match the class name, and there is no return type.

  • this.variableName: A keyword that refers to the current object's instance variable. It is used to disambiguate between instance variables and parameters or local variables that have the same name.

  • null: A special literal representing a reference that does not point to any object. An object variable that has been declared but not initialized with new has a value of null.

Core Code Examples & Terminology

  • Constructor: A special block of code that initializes a newly created object. It is called automatically when an object is instantiated using the new keyword.

  • Instance Variable: A variable declared within a class but outside any method. Its value defines the state of a specific object instance.

  • Parameter: A variable in a constructor or method declaration that accepts a value (an argument) when the constructor or method is called.

  • Overloading: Defining multiple constructors (or methods) in the same class with the same name but different parameter lists (i.e., different number, type, or order of parameters).

  • Default Constructor: A no-argument constructor that Java automatically provides if, and only if, no other constructors are explicitly defined in the class. It initializes instance variables to their default values (0, false, null).

  • Core Snippet 1: Defining a Constructor

    
    public class Student {
    
        private String name;
    
        public Student(String studentName) {
    
            this.name = studentName;
    
        }
    
    }
    

    This code defines a constructor for the Student class that initializes the name instance variable.

  • Core Snippet 2: Calling a Constructor

    
    // In a main method or other method
    
    Student newStudent = new Student("Alice");
    

    This code creates a new Student object by calling its constructor with the argument "Alice".

Core Skill Check

  • Code Tracing: What is the final value of p.price after this Java code runs: public class Product { private int price; public Product(int p) { this.price = p + 10; } } Product p = new Product(50);?

  • Debugging: Identify the compile-time error in this Java code: public class Circle { private int radius; public void Circle(int r) { this.radius = r; } }.

  • Application: Write a single line of Java code that creates a Car object named myCar using a constructor that takes the car's model "SUV" and year 2023 as arguments.

Common Misconceptions & Errors

  1. Adding a Return Type to a Constructor: If you write public void MyClass(), you have accidentally created a regular method named MyClass, not a constructor. The compiler will not use it to initialize objects, which can lead to unexpected behavior.

  2. Forgetting this.: When a parameter name is the same as an instance variable name (e.g., public Student(String name)), writing name = name; inside the constructor does nothing. The parameter is assigned to itself, and the instance variable remains at its default value (null). Always use this.name = name; in this situation.

  3. The Default Constructor Vanishes: Java provides a free, invisible, no-argument constructor only if you write no constructors yourself. The moment you define any constructor (e.g., one that takes parameters), the default one is no longer supplied. If you still need a no-argument constructor, you must write it explicitly.

  4. Confusing Declaration and Instantiation: The line Rectangle rect; only declares a variable that can hold a reference to a Rectangle object; its initial value is null. The object itself is not created until you execute rect = new Rectangle();.

Summary

Constructors are the gatekeepers of object creation in Java. They are special, non-returning code blocks named after their class, whose sole responsibility is to initialize an object's instance variables. By using the new keyword, we invoke a constructor to build a new object and ensure it begins its existence in a valid and well-defined state. Through parameters and overloading, constructors offer a flexible and robust mechanism for creating objects tailored to specific needs. Mastering constructors is a critical step toward writing reliable and maintainable object-oriented code.