3.4 Constructors
💻AP Computer Science A Unit 3 Review
3.4 Constructors
💻 AP Computer Science A
A constructor sets the starting state of an object by giving values to its instance variables when you use new. When a constructor runs, memory is allocated for the object and a reference to that object is returned. For AP Computer Science A, check that constructors have the class name, no return type, and enough information to initialize the object's fields.
The free-response class design question gives you a specification table and asks you to write a class with a header, private instance variables, constructors, and methods.
How Constructors Set Up a New Object
- A constructor has the same name as the class and has no return type, not even
void. - A constructor should initialize every instance variable so the object starts in a valid state.
- Constructor parameters provide the data used to set instance variables; without parameters, you set fixed starting values.
- If you write no constructor, Java supplies a default no-parameter constructor and sets instance variables to defaults:
intis 0,doubleis 0.0,booleanis false, and any reference type is null. - When a constructor parameter is a mutable object, store a copy of it so outside code cannot change your object's internal state later.
- Use
this.variableNamewhen a parameter has the same name as an instance variable so you assign to the right one.
Core Concepts
What a Constructor Does
A constructor sets the initial state of an object. State means the object's attributes and their values at a given time, defined by its instance variables. An object has a has-a relationship with its instance variables, which means each object holds its own copy of them as part of its data. A Student object has a name, a grade level, and a GPA, and two different Student objects can store different values for each one.
When a constructor is called with new, memory is allocated for the object and a reference to it is returned and stored in your variable.
</>Javapublic class Student { private String name; private int gradeLevel; private double gpa; // Constructor - same name as class, no return type public Student(String studentName, int grade) { name = studentName; gradeLevel = grade; gpa = 0.0; } } // Using the constructor Student alice = new Student("Alice", 11); // Constructor runs, reference stored in alice
Three things to notice: the constructor name matches the class name, there is no return type, and it initializes the instance variables.
Parameterized vs No-Parameter Constructors
A parameterized constructor takes parameters and uses them to set instance variables, so you can create an object with meaningful values right away.
</>Javapublic class Timer { private int seconds; private boolean isRunning; public Timer(int initialSeconds) { seconds = initialSeconds; isRunning = false; } } Timer timer = new Timer(60); // Starts at 60 seconds
A constructor with no parameters sets fixed starting values instead.
</>Javapublic class Timer { private int seconds; private boolean isRunning; public Timer() { seconds = 0; isRunning = false; } } Timer timer = new Timer(); // Starts at 0 seconds
The Default Constructor and Default Values
If you do not write any constructor, Java provides a no-parameter constructor called the default constructor. It sets each instance variable to the default value for its type:
| Attribute type | Default value |
|---|---|
int | 0 |
double | 0.0 |
boolean | false |
reference type (such as String or ArrayList) | null |
</>Java// No constructor written public class Point { private int x; private int y; // Java provides: public Point() { } -> x is 0, y is 0 } Point p = new Point(); // This works
Once you write your own constructor, Java does not provide the default one. So if you write a parameterized constructor and still want to create objects with no arguments, you must write a no-parameter constructor yourself.
</>Javapublic class Point { private int x; private int y; public Point(int xCoord, int yCoord) { x = xCoord; y = yCoord; } } Point p1 = new Point(3, 4); // Works // Point p2 = new Point(); // Will not compile - no no-parameter constructor
Initializing Reference Type Instance Variables
Reference type instance variables default to null. If a method tries to use a null collection, you get a NullPointerException. Initialize collections inside the constructor so the object is ready to use.
</>Javapublic class Student { private String name; private ArrayList<String> courses; public Student(String studentName) { name = studentName; courses = new ArrayList<>(); // Create the list so it is not null } public void addCourse(String course) { courses.add(course); // Works because courses was initialized } }
Copying Mutable Constructor Parameters
When a constructor parameter is a mutable object, such as an ArrayList, storing the parameter directly means your instance variable and the outside variable point to the same object. Outside code could then change your object's internal state. To prevent this, initialize your instance variable with a copy of the parameter.
</>Javapublic class Roster { private ArrayList<String> students; public Roster(ArrayList<String> incoming) { // Store a copy, not the same reference students = new ArrayList<>(incoming); } }
Now changes to the original incoming list outside the class do not affect the students list inside the object.
Handling Parameter and Instance Variable Name Conflicts
When a parameter has the same name as an instance variable, the name refers to the parameter inside the constructor. Use this. to assign to the instance variable.
</>Javapublic class Person { private String name; private int age; public Person(String name, int age) { this.name = name; // this.name is the instance variable this.age = age; // this.age is the instance variable } }
Without this., writing name = name; just assigns the parameter to itself and leaves the instance variable unchanged. You could also avoid the conflict by using different parameter names.
Writing Constructors and Tracing Object Creation
Free Response: On the class design free-response question, you build a class from a specification. Your constructor should:
- Match the class name and have no return type.
- Assign every private instance variable so the object starts in a valid state.
- Use the constructor parameters listed in the specification to set the matching instance variables.
- Store a copy of any mutable object parameter when the specification expects the object to be independent.
Build the constructor before the methods, because your methods rely on the instance variables it sets.
Code Tracing: For multiple-choice and tracing questions:
- When you see
new ClassName(args), follow the matching constructor and track what each instance variable becomes. - If an instance variable is never assigned and no constructor sets it, apply the default value: 0 for
int, 0.0 fordouble, false forboolean, null for a reference type. - Watch for a parameter that shares a name with an instance variable. Without
this., the instance variable does not change.
Common Trap: A method like public void Student() with a return type is a regular method, not a constructor, even though its name matches the class. A real constructor has no return type at all.
Common Misconceptions
- Misconception: A constructor is a normal method you call by name.Actually: A constructor is not a normal method you call by name. It runs when you use
new, and it never has a return type, not evenvoid. - Misconception: Writing
voidbefore something with the class's name makes it a constructor.Actually: Writingvoidbefore something with the class's name makes it an ordinary method, so Java still uses the no-argument default constructor and your "constructor" never runs on creation. - Misconception: The default constructor exists even when you write a constructor.Actually: The default constructor only exists when you write no constructors at all. Once you write any constructor, you must add a no-parameter one yourself if you want it.
- Misconception: Default values are blank or undefined.Actually: Default values are not blank or undefined. Numbers start at 0 or 0.0, booleans start at false, and reference types start at null until you assign them.
- Misconception: A null reference type instance variable is an empty
ArrayList.Actually: A null reference type instance variable is not an emptyArrayList. You must create the object withnewbefore calling methods on it, or you get aNullPointerException. - Misconception: Storing a mutable parameter directly is the same as copying it.Actually: Storing a mutable parameter directly is not the same as copying it. Without a copy, outside code still shares the same object and can change your object's state.
Related AP Computer Science A Guides
Practice Questions for 3.4
1 of 10
Consider the following class definition for an employee record system.
</>Javapublic class EmployeeRecord { private int empId; private int deptId; private int roleId; /* missing constructor */ }
Which of the following correctly replaces /* missing constructor */ to initialize the instance variables using parameters that share the exact same names?
A.
</>Javapublic EmployeeRecord(int empId, int deptId, int roleId) { this.empId = deptId; this.deptId = deptId; this.roleId = deptId; }
B.
</>Javapublic EmployeeRecord(int empId, int deptId, int roleId) { this.empId = empId; this.deptId = deptId; this.roleId = roleId; }
C.
</>Javapublic EmployeeRecord(int empId, int deptId, int roleId) { this.empId = empId; this.deptId = empId; this.roleId = empId; }
D.
</>Javapublic EmployeeRecord(int empId, int deptId, int roleId) { this.empId = deptId; this.deptId = roleId; this.roleId = empId; }
Vocabulary
The following words are mentioned explicitly in the AP® course framework for this topic.Term | Definition |
|---|---|
attribute | The data or properties that define the state of an object or class. |
constructor | A special method that is called to create and initialize an object of a class, having the same name as the class. |
constructor parameters | Data passed to a constructor that is used to initialize instance variables with specific values. |
default constructor | A no-parameter constructor automatically provided by Java when no constructor is explicitly written; initializes instance variables to default values. |
default values | The initial values automatically assigned to instance variables by the default constructor based on their data type (0 for int, 0.0 for double, false for boolean, null for reference types). |
has-a relationship | A relationship between an object and its instance variables, indicating that an object has certain attributes. |
instance variable | A variable that belongs to an object and can be accessed throughout the class, as opposed to a local variable that is limited to a specific block of code. |
mutable object | An object whose state can be changed after it is created; when used as a constructor parameter, a copy should be made to prevent external modification. |
object's state | The current values of all instance variables belonging to an object at a given time. |
See Fiveable more often in Google
Mark Fiveable as a preferred source and Google is more likely to show you our guides in Top Stories, with a "preferred" badge in AI Mode and AI Overviews.