this()
- Java course
- Intermediate
- Lesson 10/116
- 5 min
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.
Practice 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.
Starter code
// Define the Box class
// Chain with this()
// Call both in mainSample 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);
}
}Expected output
1 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the this() call
class Box {
int size;
Box() {
____(1);
}
Box(int s) { size = s; }
}
class Box {
int size;
Box() {
this(1);
}
Box(int s) { size = s; }
}
Explanation: this(1) calls the second constructor.
2 Match the this() rules
| Term | Meaning |
|---|---|
this() |
Constructor call |
first line |
Position rule |
this(1) |
Parameterized call |
code duplication |
Prevented issue |
3 Where must the this() call be?
- Outside the class
- At the first line of the body Correct answer
- In the middle of the body
- At the last line of the body
Explanation: At the first line of the body — this() must be first.