How can I call one constructor from another in Java?
How can I call one constructor from another in Java?
530
21-Jul-2023
Updated on 22-Jul-2023
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 thenameproperty of the object. Themain()method creates a newPersonobject and prints the value of thenameproperty.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.