4

Hi I am just learning about constructor chaining in Java and had some questions...

  1. 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.

  2. 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();
        }
    }
    
arshajii
  • 127,459
  • 24
  • 238
  • 287
jimbo123
  • 289
  • 3
  • 7
  • 13
  • There's only one instance of `Employee` created whether or not you chain ctors. The purpose of chaining ctors is to prevent duplicate logic, although you could also use initialization methods called from various ctors. – Dave Newton Jul 14 '13 at 15:07

5 Answers5

7

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.

Adrian Jandl
  • 2,985
  • 4
  • 23
  • 30
4

Chaining constructors like this is useful to avoid repeating code, and helps with maintainability:

public MyClass(int x, double y, String z) {
    // set fields
}

public MyClass() {  // i.e. a constructor that uses default values
    this(42, 4.2, "hello world");  // x is 42, y is 4.2, and z is "hello world"
}

If we didn't use the chain, and wanted to change how the x argument (for example) is processed when constructing an instance of MyClass, we would have to change code in both constructors. With the chain, we only need to change one of them.

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • I need to let that sink in my head for a bit. I still don't understand why a person can't just use the constructor with 3 arguments. – jimbo123 Jul 14 '13 at 15:18
  • 3
    @jimbo123 They can, but why would they if they want the fields to be filled with their "default" values? – arshajii Jul 14 '13 at 15:24
2

1) As others have said, it's for code maintenance, basically the idea is that you only write one piece of code once, which means you only need to edit it once, there is no risk of overlooking something when editing your methods and the two accidentally becoming different.

Personally I tend to use this differently than in your example. Like so:

Employee() {
    setupStuff();
}

Employee(String name) {
    this();
    this.setName(name);
}

This is a nice way of doing things, because potentially your setter can be way more complicated than just setting a member in the class. So basically what this does is puts calling the empty constructor and then a setter into a single method, making it much easier for anyone using the class.

2) The constructor being called doesnt't create a different object at all, it creates this object. Note that there is no new keyword used. Basically you're just calling a different method inside your constructor, except that method happens to also be a constructor.

Marconius
  • 683
  • 1
  • 5
  • 13
1
  1. Every time you want to allow constructing an object wit default values, and also want to allow creating the same object with non-default values. Let's imagine a DateTime class. You could want to initialize it with the current time by default, or with a specific time. Imagine a Car class. You could imagine constructing it with Black as the default color, or with a specific color. This kind of situation is very common. See java.util.ArrayList or java.util.Locale, for concrete examples.

  2. It's stored in the name field. So you access it, from the object itself, with this.name (this being optional, just as in the getName() method).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

How do I access this new "James Bond" object for future use?

Because you saved the values of name and salary as fields of your employee class, then inside the employee class you can use those fields, and outside your employee class you can use the getter/setter methos of your employee class

David Hofmann
  • 5,683
  • 12
  • 50
  • 78
  • But what about the original object? For example, when I call the constructor with no arguments, a normal object should be created as well as the "James Bond" object right? – jimbo123 Jul 14 '13 at 15:16
  • 3
    No. A single object is constructed. The no-arg constructor simply delegates to the with-args constructor, to create a single object. – JB Nizet Jul 14 '13 at 15:17