AP Computer Science A · Unit 3: Class Creation
3.2 Constructors
What is a constructor?
A constructor is a special method that initializes a new object's instance variables when it's created with `new`. It has the same name as the class and no return type (not even `void`). Constructors run automatically when an object is instantiated, setting up its initial state.
Default vs. parameterized constructors
If no constructor is written, Java provides a default constructor that sets fields to default values (0, false, null). A parameterized constructor accepts arguments to set instance variables to specific values, often using `this.field = parameter` when names match. Classes can have multiple constructors (overloading) with different parameter lists.
Using this in constructors
The keyword `this` refers to the current object. It resolves naming conflicts between parameters and instance variables (`this.x = x;`) and can call another constructor in the same class via `this(args)` as the first statement, avoiding duplicate initialization code.
Key terms
- Constructor
- A special method that initializes a new object's instance variables; shares the class name and has no return type.
- Default constructor
- A constructor automatically provided by Java when none is written, setting fields to default values.
- this keyword (in constructors)
- Refers to the current object; used to distinguish instance variables from parameters or to call another constructor.
- Constructor overloading
- Defining multiple constructors in a class, each with a different parameter list, to allow varied object initialization.
- this(args) call
- A call to another constructor in the same class; must be the first statement in the calling constructor.
Try an AP-style question
Code
public class Book {
private String title;
public Book(String t) { title = t; }
}What does the constructor do?
- Sets the title instance variable
- Returns the title
- Creates a new String class
- Prints the title
Show the answer
A. Initializes state.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 3.2 free in APrep