ACSA Exam Prep
Unit 3 · Class Creation · Topic 3.4

Constructors

Skill 2.BSkill 3.B

Big idea: A constructor gives a brand-new object its starting state. Any instance variable it doesn't set keeps its default value.

Learning objectives
  • Develop code to declare instance variables for the attributes to be initialized in the body of the constructors of a class.

Setting the initial state

An object's state is its attributes and their current values. The constructor's job is to give every instance variable a sensible value, usually from its parameters.

Instance variables you don't assign get defaults: 0 for int, 0.0 for double, false for boolean, and null for references.

public class Student {
  private String name;
  private int grade;
  private boolean active;

  public Student(String n) {
    name = n;
    // grade and active get default values: 0 and false
  }

  public Student(String n, int g) {
    name = n;
    grade = g;
    active = true;
  }

  public String toString() {
    return name + " " + grade + " " + active;
  }
}

Overloaded constructors and defaults

Code
Student a = new Student("Mo");
Student b = new Student("Ivy", 11);
System.out.println(a);
System.out.println(b);
Output
Mo 0 false
Ivy 11 true

The default constructor

If you write no constructor at all, Java provides a no-parameter one that leaves every instance variable at its default. Once you write any constructor, that free one disappears.

Code
Item it = new Item();
System.out.println(it.getQty() + " " + it.getName());
Output
0 null

The local-variable trap

Writing a type in front of a name inside the constructor declares a new local variable. The instance variable is left at its default.

Code
Box b = new Box(5);
System.out.println(b.getSize());
Output
0
Key points
  • A constructor sets the initial state, giving every instance variable a value.
  • Instance variables form a has-a relationship (a Student has a name).
  • Defaults: int 0, double 0.0, boolean false, references null.
  • With no constructor written, Java supplies a no-parameter default constructor.
  • When given a mutable object, a constructor should store a copy so outside code can't change the object's state.
Watch out
  • A constructor has no return type, not even void. public void Box() is a method, not a constructor.
  • int size = s; in a constructor creates a local variable and leaves the instance variable at 0.
Quick check
Is public Cube(int side) a valid constructor for class Cube? What about public void Cube()?
Show answer
The first is. The second has a return type, so it is an ordinary method named Cube.