Advantages of Constructor Overloading

constructor, java, overloading

Solution

Constructor overloading is very useful for simulate default values, or to construct an object from an already existing instance (copy) Here is an example:

public class Color {

    public int  R, G, B, A;

    // base ctr
    public Color(int R, int G, int B, int A) {
        this.R = R;
        this.G = G;
        this.B = B;
        this.A = A;
    }

    // base, default alpha=255 (opaque) 
    public Color(int R, int G, int B) {
        this(R, G, B, 255);
    }

    // ctr from double values
    public Color(double R, double G, double B, double A) {
        this((int) (R * 255), (int) (G * 255), (int) (B * 255), (int) (A * 255));
    }

    // copy ctr
    public Color(Color c) {
        this(c.R, c.G, c.B, c.A);
    }

}

Here, the first constructor is very simple. You specify R,G,B & Alpha value for a color.

While this is enough to use the Color class, you provide a second constructor, liter, which auto assign 255 to alpha if not specified by the user.

The third ctr shows that you can instantiate your Color object with double between 0. and 1. instead of integers.

The last one takes an Color as unique argument, it copies the given object.

The benefits lies also in the fact that the first constructor is always called, and you can use that to manually count your instances. Let say you have a `private static int count=0` attribute, you can track the number of Color instance like this:

    // base ctr
    public Color(int R, int G, int B, int A) {
        this.R = R;
        this.G = G;
        this.B = B;
        this.A = A;
        ++count;
    }

`count`is incremented from any constructor.

Problem

I am very new to Java and trying to learn the subject, having previous programming exposure in only HTML/CSS. I have started with Herbert Schildt and progressed through a few pages. I am unable to understand the exact advantages of Constructor Overloading. Isn't it easier to Overload Methods using single constructor for flexibility? Moreover if I am trying to use constructor overloading to use one object to initialize another, there are simpler ways to do it! So what are the benefits and in which situation should I use Constructor Overloading.

Original source

Related problems