0

What is constructor chaining and how is it achieve in java, please give me with example

  • Why don't you put forward what you think, and why you think it? (As opposed to asking us to find one of the many tutorials on the net for you..) – Andrew Thompson Dec 24 '13 at 09:56

2 Answers2

1

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");
    }
}
Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68
  • 1
    This is called telescoping constructor. Constructor chaining is calling parents constructor. – Mikhail Dec 24 '13 at 10:56
  • I've seen this term in use here on SO the way I described (i.e. [link](http://stackoverflow.com/questions/4183256/constructor-chaining-in-java)). Googling for telescoping constructor gives out J. Bloch's quote, so I presume these two might be synonyms. – Andrey Chaschev Dec 24 '13 at 11:26
0

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130