3.04 Constructors
Learn what Java constructors are, why they exist, and how to write one to initialize objects.
- Reference Guide
- College Board Requirements
- Lesson Plan
- Tech Talk
- Code Runner Challenge
- Code Runner Challenge
- Code Examples
- Hacks & Practice Tasks
- Popcorn Hack
- Code Runner Challenge
- Homework Hack
- Code Runner Challenge
- References
Reference Guide
Key Topics
| Term | Definition | Example |
|---|---|---|
| Constructor | Runs when new is called. Sets the object’s fields. |
public Student(String name, int grade) |
new keyword |
Triggers the constructor and creates the object. | new Student("Alex", 11) |
| Parameter | A value passed in when calling new. |
String name, int grade |
| Field | A variable that belongs to an object. | String name; inside the class |
this |
Refers to the current object being built. | this.name = name; |
| Default value | What Java uses when no constructor sets a field. | null for Strings, 0 for ints |
Constructor Anatomy
| Part | What it is |
|---|---|
public Student(...) |
The constructor - must have the same name as the class |
String name, int grade |
Parameters - values you pass in when using new |
this.name |
The field on the object being built |
name (no this.) |
The parameter that was passed in |
new Student(...) |
The keyword that triggers the constructor |
Picking a Type
| Field holds… | Use |
|---|---|
| Words / names | String |
| Whole numbers | int |
| Decimals | double |
| True / False | boolean |
| Single letter | char |
College Board Requirements
This lesson addresses the following AP CSA Essential Knowledge statements:
- MOD-2.B.1 - A class contains constructors that are invoked to create objects.
- MOD-2.B.2 - A constructor is defined with the same name as the class.
- MOD-2.B.3 - Constructors may take parameters to set the initial state of an object.
- MOD-2.B.4 - If no constructor is written, Java provides a no-argument constructor that sets fields to default values (
null,0,false).
“Constructors are used to set the initial state of an object. The keyword
newfollowed by a call to a constructor creates an object.”
- College Board AP CSA CED, p. 77
Lesson Plan
Learning Objective: Understand what a constructor is, why it exists, and how to write one.
Success Criteria: You can write a constructor for a given class that takes parameters and sets fields correctly.
Tech Talk
When you order a custom hoodie online, you fill out a form - your size, color, and name to put on the back. The moment you hit “place order,” the factory takes that information and builds your hoodie with those exact values. You get back a finished product, ready to wear.
A constructor is the same idea. When you write new Student("Alex", 11), you’re placing an order. The constructor is the factory - it takes your inputs and builds a finished object with those values already set. You get back a ready-to-use object, not an empty one.
A class is just a blueprint. A constructor is what actually builds it. It runs once, automatically, the moment you write new. Without a constructor, every field defaults to null or 0.
Code Runner Challenge
Try running the code below and observe what happens without a constructor:
Run this and observe the output. Then think: why are the values null and 0?
class Student {
String name;
int grade;
// no constructor - Java fills fields with defaults
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.name); // null
System.out.println(s.grade); // 0
}
}
Code Runner Challenge
Run this and observe the output. Then think: why are the values null and 0?
View IPYNB Source
// CODE_RUNNER: Run this and observe the output. Then think: why are the values null and 0?
class Student {
String name;
int grade;
// no constructor - Java fills fields with defaults
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.name); // null
System.out.println(s.grade); // 0
}
}
Main.main(null);
Code Examples
A. Simple - the problem without a constructor
No constructor means Java defaults every field to null or 0.
class Student {
String name;
int grade;
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.name); // null
System.out.println(s.grade); // 0
}
}
Main.main(null);
B. Intermediate - adding a constructor
The constructor guarantees every Student starts with a real name and grade.
class Student {
String name;
int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Alex", 11);
System.out.println(s.name); // Alex
System.out.println(s.grade); // 11
}
}
Main.main(null);
C. Complex - two objects from the same constructor
One constructor builds unlimited objects - each gets its own copy of the fields.
class Student {
String name;
int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Alex", 11);
Student s2 = new Student("Jordan", 10);
System.out.println(s1.name + " " + s1.grade);
System.out.println(s2.name + " " + s2.grade);
}
}
Main.main(null);
Hacks & Practice Tasks
Popcorn Hack
Task: The Pet class below has two fields but no constructor. Write one that sets them. Hit Run - you should see: Buddy is a dog
Write a constructor for Pet so each object starts with a real name and type. Hit Run - you should see: Buddy is a dog
class Pet {
String name;
String type;
// write your constructor here
}
public class Main {
public static void main(String[] args) {
Pet p = new Pet("Buddy", "dog");
System.out.println(p.name + " is a " + p.type);
}
}
Code Runner Challenge
Write a constructor for Pet so each object starts with a real name and type. Hit Run - you should see: Buddy is a dog
View IPYNB Source
// CODE_RUNNER: Write a constructor for Pet so each object starts with a real name and type. Hit Run - you should see: Buddy is a dog
class Pet {
String name;
String type;
// write your constructor here
}
public class Main {
public static void main(String[] args) {
Pet p = new Pet("Buddy", "dog");
System.out.println(p.name + " is a " + p.type);
}
}
Main.main(null);
Homework Hack
Task: The Book class below has three fields but no constructor. Write one that sets all three, then create two Book objects and print their info.
Expected output:
The Alchemist by Paulo Coelho, 208 pages 1984 by George Orwell, 328 pages
Write a constructor for Book that sets title, author, and pages. Hit Run and check both lines match the expected output.
class Book {
String title;
String author;
int pages;
// write your constructor here
}
public class Main {
public static void main(String[] args) {
Book b1 = new Book("The Alchemist", "Paulo Coelho", 208);
Book b2 = new Book("1984", "George Orwell", 328);
System.out.println(b1.title + " by " + b1.author + ", " + b1.pages + " pages");
System.out.println(b2.title + " by " + b2.author + ", " + b2.pages + " pages");
}
}
Code Runner Challenge
Write a constructor for Book that sets title, author, and pages. Hit Run and check both lines match the expected output.
View IPYNB Source
// CODE_RUNNER: Write a constructor for Book that sets title, author, and pages. Hit Run and check both lines match the expected output.
class Book {
String title;
String author;
int pages;
// write your constructor here
}
public class Main {
public static void main(String[] args) {
Book b1 = new Book("The Alchemist", "Paulo Coelho", 208);
Book b2 = new Book("1984", "George Orwell", 328);
System.out.println(b1.title + " by " + b1.author + ", " + b1.pages + " pages");
System.out.println(b2.title + " by " + b2.author + ", " + b2.pages + " pages");
}
}
Main.main(null);
References
College Board. (2020). AP computer science A course and exam description. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description.pdf
Oracle. (n.d.). Providing constructors for your classes. Oracle Java Tutorials. https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html