In Java, chain constructor refers to a technique where one constructor calls another constructor within the same class. This is achieved by using the "this" keyword, followed by the parameter list of the constructor that is being called.
Here's an example of a class with multiple constructors, where one constructor calls another constructor using the chain constructor technique:
public class Person { private String name; private int age; // Default constructor public Person() { this("John Doe", 30); // Call parameterized constructor } // Parameterized constructor public Person(String name, int age) { this.name = name; this.age = age; } // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
this example, the default constructor calls the parameterized constructor using the "this" keyword. This ensures that the name and age fields are initialized with default values ("John Doe" and 30, respectively) if no values are provided when creating a new Person object using the default constructor.