# Constructor Chaining in Java

When creating multiple constructors, I usually do the following;

public ConstructorName(int count)
{
this(count, 0);
}

public ConstructorName(String count)
{
this(Integer.parseInt(count), 0);
}

public ConstructorName(int count, int other)
{
// Do something here
}


However, I can also do it this way;

public ConstructorName(String count)
{
this(Integer.parseInt(count)); // Chain to the constructor that just takes a number
}

public ConstructorName(int count)
{
this(count, 0);
}

public ConstructorName(int count, int other)
{
// Do something here
}


Is there any actual difference here? Which would be better to use when coding?

• The first option will be slightly more efficient. Less switching scopes = less time wasted unnecessarily popping stuff on and off the stack. – w4etwetewtwet Jul 29 '13 at 19:24

Doesn't answer the question directly, but its far more better not to overload constructors/function

For example:

class ClassName
{
static public ClassName createFromCountString(string count)
{
return new ClassName(Integer.parseInt(count), 0);
}

static public ClassName createFromCount(int count)
{
return new ClassName(count, 0);
}

static public ClassName createFromCountAndOther(int count, int other)
{
return new ClassName(count, other);
}

private ClassName(int count, int other)
{
// do something here
}
}

• How can you write this() outside a constructor? – Anirban Nag 'tintinmj' Jul 30 '13 at 4:31
• @tintinmj the methods all belong to the ClassName class – Quonux Jul 30 '13 at 13:53
• @Quonux first of all you can't use this inside static method. Second you can call a constructor ONLY inside from another constructor. – Anirban Nag 'tintinmj' Jul 30 '13 at 14:08
• @tintinmj ok i corrected it, and you can't call it this way in java, but its possible in d, but it wasn't real java so i changed it – Quonux Jul 30 '13 at 14:20
• @tintinmj calling the constructor outside of a static function works ideone.com/Wawrd1 – Quonux Jul 30 '13 at 14:27

If there is more than one way to construct an instance, then static factory methods backed by one private constructor, can really help readability, since they can be named differently.

Range halfOpen = Range.largerThan(5);
Range closed = Range.between(7, 12);


If it is really about setting some properties and not others, then the Builder pattern can be what you want.

Person john = Person.named("John")
.lastName("Lennon")
.gender(Male)
.yearOfBirth(1940)
.build();


Both of these approaches also allow for hiding which implementation class is really returned. Our Person instance may be an instance of subclass Man, and the half open Range may be an instance of HalfOpenRange. Both methods allow returning a cached instance, rather than an actual new instance.