In Java, you can call one constructor from another using the this() keyword. The
this() keyword refers to the current object.
To call one constructor from another, you need to use the this() keyword followed by the name of the constructor you want to call. The constructor you want to call must be defined in the same class as the constructor that is calling it.
Here is an example of how to call one constructor from another in Java:
Java
class Person {
public Person() {
// This is the default constructor.
}
public Person(String name) {
// This constructor takes a name parameter.
this(); // Call the default constructor first.
this.name = name;
}
private String name;
}
In this example, the Person() constructor is the default constructor. The
Person(String name) constructor takes a name parameter. The first line of the
Person(String name) constructor calls the Person() constructor first. This is done to ensure that the fields of the
Person class are initialized before the name property is set.
Here is another example:
Java
class Person {
public Person(String name, int age) {
// This constructor takes a name and age parameter.
this(name); // Call the constructor that takes a name parameter first.
this.age = age;
}
public Person(String name) {
// This constructor takes a name parameter.
this.name = name;
}
private String name;
private int age;
}
In this example, the Person(String name, int age) constructor calls the
Person(String name) constructor first. This is done to ensure that the name property is initialized before the age property is set.
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.
In Java, you can call one constructor from another using the
this()keyword. Thethis()keyword refers to the current object.To call one constructor from another, you need to use the
this()keyword followed by the name of the constructor you want to call. The constructor you want to call must be defined in the same class as the constructor that is calling it.Here is an example of how to call one constructor from another in Java:
Java
In this example, the
Person()constructor is the default constructor. ThePerson(String name)constructor takes a name parameter. The first line of thePerson(String name)constructor calls thePerson()constructor first. This is done to ensure that the fields of thePersonclass are initialized before the name property is set.Here is another example:
Java
In this example, the
Person(String name, int age)constructor calls thePerson(String name)constructor first. This is done to ensure that the name property is initialized before the age property is set.