Sure! 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. The
this(...) keyword is used to invoke another constructor in the same class.
The following code shows how to call one constructor from another in Java:
class Person {
private String name;
public Person() {
this("John Doe"); // Calls the constructor with the parameter "John Doe"
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.getName()); // Prints "John Doe"
}
}
In the code above, the Person() constructor calls the Person(String name) constructor. The
Person(String name) constructor initializes the name property of the object. The
main() method creates a new Person object and prints the value of the
name property.
Here are some important things to note about calling one constructor from another in Java:
The this(...) keyword must be the first statement in the constructor that is calling another constructor.
The constructor that is being called must be in the same class as the constructor that is calling it.
The parameters of the constructor that is being called must match the parameters of the constructor that is calling it.
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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure! 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.