What is constructor chaining and how is it achieve in java, please give me with example
2 Answers
Constructor chaining is a technique when all your constructors reference a single constuctor in the class providing default values for omitted parameters. The goal is to clarify object construction and reduce redundancy:
public static final class Foo{
private final String a;
private final String b;
private final String c;
private final String d;
public Foo(String a, String b, String c, String d){
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public Foo(String a, String b, String c){
this(a, b, c, "d");
}
public Foo(String a, String b){
this(a, b, "c");
}
}
2 Comments
Mikhail
This is called telescoping constructor. Constructor chaining is calling parents constructor.
Andrey Chaschev
I've seen this term in use here on SO the way I described (i.e. link). Googling for telescoping constructor gives out J. Bloch's quote, so I presume these two might be synonyms.
Constructor chaining is used when you have public nested classes.
e.g.
public class A {
public class B {
public class C {
}
}
}
to create a C you need a B which needs as A.
C c = new A().new B().new C();
IMHO this breaks encapsulation and you should have a method in each class which can return a nested class rather than create them externally.