Java
this()
Learn to call constructors with this().
Chaining with this()
Inside a constructor you can call another constructor of the same class with this(...). This is called constructor chaining. The this() call must be the first statement in the body; otherwise a compile error occurs.
Example: class Box { int size; Box() { this(1); } Box(int s) { size = s; } }. Here the no-arg constructor calls the second one with this(1). This approach prevents code duplication; shared logic stays in one constructor, others call it. Maintenance is easier.
Why use this()?
this() reduces code duplication. Instead of rewriting assignment logic in one constructor that already exists in another, you call it with this(). All shared logic stays in one place; changes happen at a single point.
Example: Suppose Box() and Box(int s) exist. Instead of writing size = 1; inside Box(), you write this(1). The size assignment stays only inside Box(int s). If the assignment logic changes, one constructor is updated; not two.
Exercise Add this() chaining to Box
Define a class named Box. Add an int size field. Write two constructors: the first is Box(int s), assigning size = s;; the second is Box(), calling the first with this(1). In main call both constructors and print the size fields on separate lines.
Show example solution
class Box {
int size;
Box(int s) {
size = s;
}
Box() {
this(1);
}
public static void main(String[] args) {
Box a = new Box();
Box b = new Box(5);
System.out.println(a.size);
System.out.println(b.size);
}
}
Test yourself
-
Complete the this() call
class Box {
int size;
Box() {
____(1);
}
Box(int s) { size = s; }
}
Show answer
class Box {
int size;
Box() {
this(1);
}
Box(int s) { size = s; }
}
-
Match the this() rules
- this()
- Constructor call
- first line
- Position rule
- this(1)
- Parameterized call
- code duplication
- Prevented issue
-
Where must the this() call be?
- Outside the class
- At the first line of the body
- In the middle of the body
- At the last line of the body
Show answer
At the first line of the body — At the first line of the body — this() must be first.
Next lesson: Default constructor