Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will constructor chaining create more than one object in Java?

If I am calling another constructor of same class using this keyword. Will it create two objects?

If so, which object will be active in below example:

Class Sample {
    int a;
    String b;

    Sample() {
        this("Hello");
        a=10;
    }

    Sample(String temp) {
        b = temp;
    }    
}

I want to know the behaviour of Constructor chaining. Please explain how it works?

like image 614
Raashith Avatar asked Jun 10 '26 15:06

Raashith


2 Answers

No, constructor chaining doesn't create an additional instance, it just executes the logic of the chained constructor, allowing you to reuse its code.

like image 102
Eran Avatar answered Jun 12 '26 07:06

Eran


No, this("Hello"); here ll call Sample(String temp) constructor, it won't create another object.

like image 34
Soumitri Pattnaik Avatar answered Jun 12 '26 08:06

Soumitri Pattnaik