Lesson Overview
This lesson explains constructors, default values, constructors with arguments, multiple constructor arguments, and constructor overloading.
What Is a Constructor?
A constructor is a special method-like block that runs when an object is created. Java calls it automatically when new is used.
When new creates an object, Java normally:
- Allocates memory for the object.
- Assigns default values to fields.
- Calls the matching constructor.
Default field values include:
| Field type | Default value |
|---|---|
| numeric types | 0 or 0.0 |
| object references | null |
boolean | false |
char | \u0000 |
A constructor must have the same name as the class and cannot have a return type.
No-Argument Constructor
A no-argument constructor accepts no values. It is often used to set initial field values.
Activity: Constructor with Initial Values
Constructor with One Argument
A constructor can receive a value when an object is created.
EmployeeId record = new EmployeeId(2470);
The value inside the parentheses is passed to the constructor.
Activity: Constructor with One Argument
Constructor with Multiple Arguments
Constructors can receive several values separated by commas. The order and type of arguments must match the constructor parameters.
Activity: Constructor with Multiple Arguments
Constructor Overloading
Constructor overloading means writing multiple constructors in the same class with different parameter lists.
If you write a constructor with parameters, Java no longer automatically provides the no-argument constructor. Add your own no-argument constructor if you still need one.
Activity: Overloaded Constructors
Laboratory Exercises
Try It: Constructors
Add a fourth Rectangle using the square constructor and print its area and perimeter.