this() vs super(): Constructor Delegation
What you'll learn: How to choose between this() and super() when delegating constructor work in Java.
The Core Difference
Both this() and super() delegate initialization work to another constructor, but they target different classes:
this()calls another constructor in the same classsuper()calls a constructor in the superclass
Think of it like asking for help: this() is like asking a coworker on your team, while super() is like asking your manager from the department above you.
When to Use this()
Use this() when you want one constructor to reuse the logic of another constructor in the same class. This is constructor overloading:
public class Book {
private String title;
private String author;
// Main constructor
public Book(String title, String author) {
this.title = title;
this.author = author;
}
// Delegates to the main constructor
public Book(String title) {
this(title, "Unknown Author");
}
}
Here, the single-parameter constructor uses this() to call its sibling constructor, avoiding duplicate initialization code.
When to Use super()
Use super() when you need to initialize the superclass part of your object:
public class EBook extends Book {
private double fileSizeMB;
// Calls the superclass constructor
public EBook(String title, String author, double fileSizeMB) {
super(title, author); // Initialize Book fields
this.fileSizeMB = fileSizeMB; // Initialize EBook field
}
}
The super() call ensures the Book portion of the EBook is properly initialized before adding EBook-specific initialization.
The Key Rule
Remember: you can only use one or the other, and it must be the first statement. You cannot call both this() and super() in the same constructor.
Key Takeaway: Use this() to delegate to another constructor in the same class; use super() to delegate to a superclass constructor. Choose based on where the initialization logic lives.