3.04 Constructors


1. 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

2. LxD Cycle Process

Empathize

Students can write a class but don’t understand how an object actually gets its data. They see new Student() and don’t know what happens next.

Define

  • POV: Students need to feel the difference between a blueprint (class) and a real object, because without that, constructors feel like arbitrary syntax.
  • Learning Goal: Students will write a constructor that sets fields using parameters.

Ideate

  • HMW: How might we make the moment new fires feel real and tangible?
  • Activity: Teacher calls new Student() on a volunteer. The student stands up and says their name and grade aloud - as if the constructor just ran on them.

Prototype

Build the lesson around the physical “You ARE the Object” activity. Students act as objects being instantiated by the teacher calling new.

Test

Tested the activity with the class. Students immediately connected parameters to fields after seeing it done on a real person.


3. 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 new followed by a call to a constructor creates an object.”

  • College Board AP CSA CED, p. 77

4. 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 (5 minutes)

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:

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);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

5. 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);

6. Hacks & Practice Tasks

Submission Safety Rules (Read First)

[!IMPORTANT]

  • Only use Java - no CSS, no HTML.
  • Do not change the class name or field names given to you.
  • Make sure your code runs and prints the expected output before submitting.

Popcorn Hack (In-Class)

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

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);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

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

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);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

7. Lesson Revisions

# Change Reason
1 Added codemirror: true to frontmatter Code Runners were not rendering on the live site
2 Converted Popcorn Hack and Homework Hack to CODE_RUNNER format Teacher feedback: students should be able to run and edit code directly from the lesson page
3 Removed answer keys from hacks Hacks are student work - answer keys should not be visible in the lesson
4 Added LxD Cycle Process section Required by teacher for all lessons
5 Fixed inject_code_runners counter bug Backtick fenced blocks in markdown cells threw off the code runner counter, causing wrong cells to be wrapped
6 Added assignment: true to frontmatter Enables the Submit Assignment widget so students can submit from the lesson page
7 Restructured all section names to match lesson 1.2 format Teacher feedback: all lessons should follow the same structure for consistency

8. Feedback Evidence

No feedback collected yet.


9. 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

Submit Assignment

Click to upload or drag and drop
PDF, ZIP, images, documents, or Jupyter notebooks (.ipynb) (Max 10MB per file)

Need to update a submission later? Open the submissions dashboard.