2

I know it is possible to call one constructor from another constructor via the use of "this".

But I would like to know is, why do we do it (i.e calling a constructor from another constructor)

Can anyone relate a simple example of where this might be actually useful ?

UnderDog
  • 3,173
  • 10
  • 32
  • 49
  • I think the term you are looking for to describe it is known as [constructor overloading](http://stackoverflow.com/questions/1182153/constructor-overloading-in-java-best-practice) – Josh M Aug 16 '13 at 17:38

3 Answers3

10

ArrayList is a nice example. The default constructor calls the constructor that takes the initial capacity of the underlying array. This looks like this:

public ArrayList()
{
    this(10);
}

public ArrayList(int capacity)
{
    objects = new Object[capacity];
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • Same goes for `new HashMap()` and of the other objects that can be created in default of specified way – dantuch Aug 16 '13 at 17:23
2

If we do not want to duplicate code:

class Foo{

    int requiredParam;
    String name;
    double optionalPrice;
    Object extraObject;
    public Foo(int rp, String name){
        this.requiredParam=rp;
        this.name=name
    }
    public Foo(int rp, String name, double op, Object e){
        this(rp, name);
        this.optionalPrice=op;
        this.extraObject=e;
    }
nanofarad
  • 40,330
  • 4
  • 86
  • 117
1

How about a simple class like this:

  class Person {

        String name;

        Person(String firstName, String lastName) {
            this(firstName + lastName);
        }

        Person(String fullName) {
            name = fullName;
        }
    }

Different constructors give you the freedom of creating similar objects in different flavors.

rocketboy
  • 9,573
  • 2
  • 34
  • 36