AP Computer Science A

💻ap computer science a review

5.2 Constructors

Verified for the 2025 AP Computer Science A examLast Updated on June 18, 2024

Constructors are special methods that bring objects to life in Java. When you create a new object using the new keyword, a constructor is called to initialize the object's state. In this section, we'll explore how constructors work, how they set initial values for instance variables, and how they establish the starting characteristics of an object. Understanding constructors is crucial for creating well-formed objects that begin their lifecycle in a proper, predictable state.

What is a Constructor?

A constructor is a special method that:

  • Has the same name as the class
  • Has no return type (not even void)
  • Is automatically called when an object is created with the new keyword
  • Sets the initial state of an object

Terms to know:

  • Private: a visibility modifier that restricts access to certain variables or methods within a class. It means that only other members of the same class can access those private elements.
  • Public: an access modifier in Java that indicates unrestricted visibility for classes, methods, and variables. Public members can be accessed from any other class or package.
public class Student {
    private String name;
    private int id;
    private double gpa;
    
    // This is a constructor
    public Student(String name, int id) {
        this.name = name;
        this.id = id;
        this.gpa = 0.0;  // Default starting value
    }
}

// Creating an object calls the constructor
Student student1 = new Student("Alex Kim", 12345);

The Role of Constructors

The primary purpose of constructors is to set the initial state of an object by:

  • Initializing instance variables with meaningful values
  • Setting up any necessary relationships with other objects
  • Ensuring the object starts in a valid state

This creates a "has-a" relationship between the object and its instance variables. For example, a Car object "has a" model name, "has a" year, and "has a" current mileage.

Constructor Parameters

Constructor parameters are local variables that:

  • Exist only within the constructor method
  • Provide data to initialize instance variables
  • Are typically named similarly to the instance variables they initialize
public class Rectangle {
    private double length;
    private double width;
    
    public Rectangle(double length, double width) {
        // Parameters length and width provide values
        // for instance variables this.length and this.width
        this.length = length;
        this.width = width;
    }
}

The this Keyword

The this keyword is used to distinguish between:

  • Instance variables (belonging to the object)
  • Parameter variables (local to the constructor)

When parameter names match instance variable names (which is common), this is necessary to avoid confusion:

public class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;  // this.name refers to the instance variable
        this.age = age;    // age by itself would refer to the parameter
    }
}

Multiple Constructors

A class can have multiple constructors with different parameter lists, known as constructor overloading:

public class Book {
    private String title;
    private String author;
    private int pages;
    
    // Constructor for fully specified book
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
    
    // Constructor for unknown page count
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
        this.pages = 0;  // Unknown page count
    }
    
    // Constructor for anonymous work
    public Book(String title) {
        this.title = title;
        this.author = "Unknown";
        this.pages = 0;
    }
}

Default Constructor

When no constructor is written for a class:

  • Java automatically provides a no-argument constructor
  • This default constructor sets instance variables to default values:
    • Numeric types (int, double, etc.): 0
    • Boolean: false
    • Reference types (objects): null
// This class has no explicit constructor
public class SimpleBox {
    private int width;
    private String label;
    private boolean isOpen;
}

// Java provides a default constructor
SimpleBox box = new SimpleBox();
// box.width is 0
// box.label is null
// box.isOpen is false

Important: If you define any constructor, Java will NOT provide the default constructor.

Constructors with Object Parameters

When a constructor parameter is a mutable object (an object that can be changed):

  • You should create a copy of the object rather than storing a reference
  • This prevents the original object from affecting your class's state
public class Course {
    private String name;
    private ArrayList<String> students;
    
    public Course(String name, ArrayList<String> roster) {
        this.name = name;
        
        // WRONG: Direct reference - changes to roster will affect students
        // this.students = roster;
        
        // CORRECT: Create a copy to prevent unwanted changes
        this.students = new ArrayList<String>(roster);
    }
}

Why Copy Mutable Objects?

Consider this example:

// Create a roster
ArrayList<String> classRoster = new ArrayList<String>();
classRoster.add("Emma");
classRoster.add("Noah");

// Create a course with this roster
Course math101 = new Course("Math 101", classRoster);

// Later, modify the original roster
classRoster.clear();  // Remove all students

// If Course used direct reference, math101 would now have no students!
// By creating a copy, math101's student list is protected

Complete Constructor Example

Here's a complete example showing proper constructor usage:

public class BankAccount {
    private String accountNumber;
    private String ownerName;
    private double balance;
    private ArrayList<String> transactionHistory;
    
    public BankAccount(String accountNumber, String ownerName, double initialDeposit) {
        this.accountNumber = accountNumber;
        this.ownerName = ownerName;
        
        // Validate initial deposit
        if (initialDeposit >= 0) {
            this.balance = initialDeposit;
        } else {
            this.balance = 0;
        }
        
        // Initialize empty transaction history
        this.transactionHistory = new ArrayList<String>();
        
        // Record initial deposit if positive
        if (initialDeposit > 0) {
            this.transactionHistory.add("Initial deposit: $" + initialDeposit);
        }
    }
    
    public BankAccount(String accountNumber, String ownerName) {
        // Call the other constructor with zero initial deposit
        this(accountNumber, ownerName, 0);
    }
}

Key Points to Remember

  • Constructors initialize the state of a new object by setting values for instance variables
  • Every constructor must initialize all instance variables, either explicitly or with default values
  • Use the this keyword to distinguish between instance variables and parameters with the same name
  • If no constructor is provided, Java supplies a default no-argument constructor
  • When a parameter is a mutable object, create a copy to prevent external changes from affecting your object
  • A class can have multiple constructors to provide different ways of creating objects

Key Terms to Review (10)

Assignment: An assignment is the act of giving a value to a variable in programming. It involves storing information into memory locations so it can be accessed and manipulated later.
Class: A class is a blueprint or template for creating objects in object-oriented programming. It defines the properties and behaviors that an object of that class will have.
Constructor: A constructor is a special method within a class that is used to initialize objects of that class. It is called automatically when an object is created and helps set initial values for its attributes.
Instance Variables: Instance variables are variables declared within a class but outside any method. They hold unique values for each instance (object) of the class and define the state or characteristics of an object.
Key Term: String: A string is a sequence of characters, such as letters, numbers, and symbols, that is used to represent text in programming. It is often enclosed in quotation marks.
Mutable Object: A mutable object is an object whose state can be modified after it is created. In other words, you can change the values of its attributes or properties.
Object's State: An object's state refers to the set of values stored in its instance variables at any given time during program execution. It represents the current condition or snapshot of an object's data.
Private: In the context of programming, private refers to a visibility modifier that restricts access to certain variables or methods within a class. It means that only other members of the same class can access those private elements.
Public: Public is an access modifier in Java that indicates unrestricted visibility for classes, methods, and variables. Public members can be accessed from any other class or package.
Student: A student is an individual who is enrolled in a school or educational institution and is actively pursuing knowledge and education.