§ 02 — 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.
04 — Activity: Constructor with Initial ValuesPro reviewer — not included in this printout.
ProReviewer — locked
Part of this subject's paid reviewers.
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.
06 — Activity: Constructor with One ArgumentPro reviewer — not included in this printout.
ProReviewer — locked
Part of this subject's paid reviewers.
Constructors can receive several values separated by commas. The order and type of arguments must match the constructor parameters.
08 — Activity: Constructor with Multiple ArgumentsPro reviewer — not included in this printout.
ProReviewer — locked
Part of this subject's paid reviewers.
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.
Pro2 reviewers locked
Part of this subject's paid reviewers. Not included in this printout.
Add a fourth Rectangle using the square constructor and print its area and perimeter.
class Rectangle {
double width;
double height;
Rectangle() {
width = 1.0;
height = 1.0;
}
Rectangle(double w, double h) {
width = w;
height = h;
}
Rectangle(double side) {
width = side;
height = side;
}
double area() { return width * height; }
double perimeter() { return 2 * (width + height); }
}
public class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(4.0, 3.0);
Rectangle r3 = new Rectangle(5.0);
System.out.println("r1 area: " + r1.area());
System.out.println("r2 area: " + r2.area() + ", perimeter: " + r2.perimeter());
System.out.println("r3 area: " + r3.area());
}
}Done with this module? Track it — your progress shows on the subject list.
Studying with blockmates? Send them this lesson.
Up next
Lesson 7: Prewritten Classes and Methods→←Previous: Lesson 5: Classes and Objects