What is the use of constructor chaining ?

classic Classic list List threaded Threaded
2 messages Options
Tiny Tiny
Reply | Threaded
Open this post in threaded view
|

What is the use of constructor chaining ?

What could be the practical scenario for using constructor chaining.  

public class Test
{
    private int x;

    public Test()
    {
        this(1);
    }

    public Test(int x)
    {
        this.x = x;
    }
}
Vikas Vikas
Reply | Threaded
Open this post in threaded view
|

Re: What is the use of constructor chaining ?

Just think of a situation where one constructor is setting 10 fields and the other constructor setting 20 fields out of which 10 are common to both. Why to repeat the code for 100 common fields in both the constructor and Why not just call one constructor from another. Its another way of Code Reuse.