Java
Constructors
Learn how objects come to life: constructors initialize state, enforce rules, and let you build powerful object-oriented programs.
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.
How Objects Are Born
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
Anatomy of a Constructor
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.
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.
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.
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
Example: BankAccount
Example: Overloaded Point
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.
The Constructor Chain
Common Mistakes
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(...)?