I’m confused about how this constructor Java usage works. If a class has two constructors and I use the this
keyword inside a method, how do I know which constructor was used to instantiate the object referred to by this
?
So I’ve been working with Java for over a decade now, and one thing that’s always consistent: the this
keyword in constructors. It always refers to the current instance of the class—no exceptions. That holds true whether you have one constructor or five.
Here’s a simple example using a Dog
class:
public class Dog {
String name;
int age;
public Dog(String name) {
this.name = name;
}
public Dog(String name, int age) {
this(name); // constructor chaining
this.age = age;
}
public void printInfo() {
System.out.println("Dog name: " + this.name + ", age: " + this.age);
}
}
No matter how you initialize it, this
in Java always points to the object being created. So if you’re looking at this constructor Java code and wondering, “Is this
different depending on which constructor?”—nope. It’s always the current instance.
Totally agree, @yanisleidi-rodriguez. I’ve run into that too while building larger apps where constructor overloading helps keep things DRY.
One cool trick is using constructor chaining with this()
to reduce duplication. So when someone talks about “this constructor Java behavior,” I always point them to this:
public class Book {
String title;
String author;
public Book(String title) {
this(title, "Unknown Author"); // constructor chaining
}
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}
When you create a new Book("Java 101")
, it’s still the same object being initialized, but we smartly routed the call through another constructor using this()
. Cleaner code, fewer bugs, and again—this
still refers to the same instance throughout. That’s the beauty of this constructor Java logic.
Yep, both your points hit the nail on the head. Just to add a fun little twist—if you’re ever in a situation where you need to track which constructor was actually used, Java won’t do it for you out of the box, but you can totally build that in yourself.
Here’s how I’ve done it in a few real-world debugging situations:
public class User {
String name;
String constructorUsed;
public User(String name) {
this.name = name;
this.constructorUsed = "One-arg constructor";
}
public User() {
this("Default");
this.constructorUsed = "No-arg constructor";
}
public void printConstructorInfo() {
System.out.println("Constructor used: " + this.constructorUsed);
}
}
Super helpful when trying to understand flow in complex systems. And don’t worry—even if you set constructorUsed
later, this
still refers to the current object. That consistency is a big plus in this constructor Java pattern—it gives you full control and clarity.