01 / 21

Java
Constructors

Learn how objects come to life: constructors initialize state, enforce rules, and let you build powerful object-oriented programs.

AP Computer Science A

What Is a Constructor?

A constructor is a special method that runs automatically when you create a new object with the new keyword. Its job is to initialize the object's instance variables so the object starts life in a valid state.

public class Dog { private String name; private int age; // Constructor public Dog(String n, int a) { this.name = n; this.age = a; } }

How Objects Are Born

new Dog(...) Constructor Initializes fields Sets valid state Dog Object name = "Rex" age = 3

When you write new Dog("Rex", 3), Java: allocates memory for the object, calls the constructor to fill in the fields, and returns a reference to the new object.

Why Constructors Matter

✓ Guaranteed Init
Every object starts with valid data: no null surprises or random defaults.
✓ Encapsulation
Callers don't need to know which fields exist: just pass the right arguments.
✓ Flexibility
Overloaded constructors let you create objects in multiple ways.

Anatomy of a Constructor

1 2 3 4 5 6 7 8 public Circle ( double r ) { this . radius = r ; } Access modifier Same name as class Parameter(s) "this" refers to current object No return type: not even void

The Default Constructor

If you write no constructors at all, Java provides a hidden default (no-argument) constructor that sets all fields to their type's default: \( 0 \) for numbers, false for booleans, null for objects.

public class Cat { private String name; // defaults to null private int lives; // defaults to 0 // No constructor written // Java auto-generates: public Cat() { } } Cat c = new Cat(); // works fine

Parameterized Constructors

A parameterized constructor accepts arguments so you can customize each object at creation time. This is the most common constructor pattern on the AP exam.

public class Student { private String name; private double gpa; public Student(String name, double gpa) { this.name = name; this.gpa = gpa; } } Student s = new Student("Alice", 3.9);

Constructor Overloading

A class can have multiple constructors with different parameter lists. Java picks the right one based on the arguments you pass. This is called overloading.

public class Rectangle { private double width, height; // Two-parameter constructor public Rectangle(double w, double h) { width = w; height = h; } // One-parameter constructor (square) public Rectangle(double side) { width = side; height = side; } }

Constructor vs Method

Constructor Method
Name Same as class name Any valid identifier
Return type None (not even void) Must declare one
Called by new keyword Dot notation on object
Invocation count Once per object creation As many times as needed
Inheritance Not inherited Inherited by subclass

How to Write a Constructor

1
Declare the constructor with the same name as the class and an access modifier (usually public).
2
List parameters that correspond to the instance variables you want to initialize.
3
Assign each parameter to its instance variable using this.field = param.
4
Add overloaded versions if callers need to create objects with different sets of information.
5
Write a no-arg constructor if you still need one: it won't exist automatically once you've written any constructor.

Example: BankAccount

public class BankAccount { private String owner; private double balance; public BankAccount(String owner, double balance) { this.owner = owner; this.balance = balance; } public double getBalance() { return balance; } }

Example: Overloaded Point

public class Point { private int x, y; // Full constructor public Point(int x, int y) { this.x = x; this.y = y; } // No-arg: defaults to origin public Point() { this.x = 0; this.y = 0; } }

Calling super() in Subclasses

When a subclass extends a superclass, its constructor must call the superclass constructor using super(...) as the first statement. If omitted, Java inserts super() (no-arg) automatically.

public class Animal { private String species; public Animal(String species) { this.species = species; } } public class Dog extends Animal { private String breed; public Dog(String breed) { super("Canine"); // must be first line this.breed = breed; } }

The Constructor Chain

Object super() Animal species = "Canine" super("Canine") Dog breed = "Labrador" runs 1st runs 2nd called first

Common Mistakes

✕ Adding void
Writing public void Dog() turns it into a regular method, not a constructor. Remove the return type.
✕ Forgetting this
If the parameter name matches the field, name = name assigns the parameter to itself. Use this.name = name.
✕ Missing no-arg
After writing a parameterized constructor, calling new Dog() fails because the default constructor no longer exists.

Constructor Summary

Type Syntax When Used
Default (auto) None written No constructors in class
No-arg (explicit) public Cls() { } Create with default values
Parameterized public Cls(int x) { } Customize at creation
Overloaded Multiple signatures Multiple creation paths
Subclass + super super(...) first line Initialize inherited fields

Question 1 of 5

Which of the following is true about constructors in Java?

Question 2 of 5

A class Book has the constructor public Book(String title, int pages). No other constructors are defined. Which line compiles?

Question 3 of 5

What does the this keyword refer to inside a constructor?

Question 4 of 5

Consider:
public class Pet { private String name; }
What happens when you execute Pet p = new Pet();?

Question 5 of 5

In a subclass constructor, what happens if you do not explicitly call super(...)?