Constructors And This
A constructor establishes an object's initial state. It has the class name, no return type, and runs as part of every matching new expression.
The keyword this refers to the current object. It is especially useful when a parameter intentionally has the same name as a field.
Start with valid state
class Lamp {
boolean on;
Lamp(boolean on) {
this.on = on;
}
}
public class Main {
public static void main(String[] args) {
Lamp deskLamp = new Lamp(true);
System.out.println("Lamp on: " + deskLamp.on);
}
}
Output:
Lamp on: true
this.on = on assigns the parameter on the right to the current object's field on the left.
If you declare any constructor, Java no longer supplies an automatic no-argument constructor. Add one explicitly only when an empty initial state makes sense.
Complete the Book constructor. Use this to distinguish each field from its parameter.