0

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

1
  • 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..) Commented Dec 24, 2013 at 9:56

2 Answers 2

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");
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is called telescoping constructor. Constructor chaining is calling parents constructor.
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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.