§ — — Object-Oriented Programming with Java
This lesson explains constructors, default values, constructors with arguments, multiple constructor arguments, and constructor overloading.
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:
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.
A no-argument constructor accepts no values. It is often used to set initial field values.
ProReviewer — locked
Drills, code labs, and full solutions.
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.
ProReviewer — locked
Drills, code labs, and full solutions.
Constructors can receive several values separated by commas. The order and type of arguments must match the constructor parameters.
ProReviewer — locked
Drills, code labs, and full solutions.
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.
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
Add a fourth Rectangle using the square constructor and print its area and perimeter.
Done with this module? Track it — your progress shows on the subject list.
Up next
Prewritten Classes and Methods→←Previous: Classes and Objects