A constructor is a special method that runs automatically when an object is instantiated. Its main purpose is to initialize the new object's instance variables, establishing its initial state.
How a Constructor Works
In object-oriented programming, a class defines the attributes and behaviours that its objects will have. When a program uses new to instantiate an object, memory is allocated for the object and its constructor is invoked.
For example, consider this Java class:
public class Student {
private String name;
private int score;
public Student(String studentName, int initialScore) {
name = studentName;
score = initialScore;
}
}
The statement below creates an object and passes two arguments to the constructor:
Student learner = new Student("Amira", 85);
The constructor's parameters receive "Amira" and 85. It assigns these values to the object's fields, so learner begins with name equal to "Amira" and score equal to 85.
| Constructor feature | Purpose |
|---|---|
| Same name as the class | Identifies it as a constructor in Java |
| No return type | A constructor is not declared with void or another return type |
| Parameters | Allow different initial values to be supplied |
| Field assignments | Establish the object's initial state |
| Automatic invocation | Occurs when an object is instantiated using new |
A class may have multiple constructors with different parameter lists. This is constructor overloading. If no constructor is declared in Java, the compiler normally supplies a default no-argument constructor; however, once any constructor is declared, that automatic constructor is not supplied.
A common misconception is that the constructor itself creates or returns the object. More precisely, new initiates object creation, while the constructor initializes the object's state.
IB Exam Technique
For B3.1, define a constructor using both ideas: it is called during instantiation and initializes instance variables. When tracing code, identify the arguments, match them to constructor parameters, and state the resulting field values. Do not describe a constructor as an ordinary method or give it a return type.