Module 3: Object-Oriented Programming
Constructors
Initialize objects and understand constructor overloading.
A constructor initializes a new object. It has the same name as its class and does not declare a return type—not even void.
A no-argument constructor#
public class Student {
private String name;
public Student() {
name = "Unknown";
}
public String getName() {
return name;
}
}
When code runs new Student(), Java calls the constructor to initialize the new object.
A parameterized constructor#
public class Student {
private final String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
The expression this.name refers to the object's field. The bare name on the right refers to the constructor parameter. The final field must be assigned during initialization and cannot be reassigned later.
Constructor overloading#
A class can provide multiple constructors with different parameter lists:
public class Rectangle {
private final int width;
private final int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public Rectangle(int side) {
this(side, side);
}
}
this(side, side) invokes another constructor in the same class and must be the first statement in that constructor.
Important rules#
- Constructors are not inherited as ordinary methods.
- If you declare no constructor, Java provides a default no-argument constructor.
- Once you declare a constructor, Java does not automatically add that default constructor.
- Constructors can be overloaded, but they cannot be overridden like instance methods.
Practice#
Create a Book class with a title and page count. Write one constructor that accepts both values, and another that supplies a reasonable default page count.