How can I call one constructor from another in Java?
How can I call one constructor from another in Java?
15521-Jul-2023
Updated on 22-Jul-2023
Home / DeveloperSection / Forums / How can I call one constructor from another in Java?
How can I call one constructor from another in Java?
Aryan Kumar
22-Jul-2023Sure! Here's how you can call one constructor from another in Java:
To call one constructor from another in Java, you can use the
this(...)
keyword. Thethis(...)
keyword is used to invoke another constructor in the same class.The following code shows how to call one constructor from another in Java:
In the code above, the
Person()
constructor calls thePerson(String name)
constructor. ThePerson(String name)
constructor initializes thename
property of the object. Themain()
method creates a newPerson
object and prints the value of thename
property.Here are some important things to note about calling one constructor from another in Java:
this(...)
keyword must be the first statement in the constructor that is calling another constructor.Constructor chaining is a powerful technique that can be used to simplify the code for creating objects. It can also be used to avoid duplicate code.