Java Constructor Chaining

constructor-chaining, java

Solution

Actually I believe the most common use of chained Constructors is when the Constructor does more than just setting the member variables.

static int numOfExamples = 0;
public Example(String name, int num)
{
    this.name = name;
    this.num = num;
    numOfExamples++;
    System.out.println("Constructor called.");
    Log.info("Constructor called");
}

public Example()
{
    this("James Bond",3);
}

That way we don't have to write the code for logging and incrementing the static variable twice, instead just chaining the constructors.

Problem

Hi I am just learning about constructor chaining in Java and had some questions... First of all could someone please explain when I would ever need to use this? Off the top of my head I seriously cannot think of a situation. In this example, within the constructor with no arguments I call another constructor. How do I access this new "James Bond" object for future use? ``` import java.util.*; class Employee { private String name; private double salary; public Employee() { this("James Bond", 34000); } public Employee(String n, double s) { name = n; salary = s; } public String getName() { return name; } public double getSalary() { return salary; } public static void main(String[] args) { Employee a = new Employee(); } } ```

Original source

Related problems