Constructor overloading is very useful for simulating default values ββor for creating an object from an 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(cR, cG, cB, cA); } }
Here, the first constructor is very simple. You specify the R, G, B, and Alpha values ββfor the color.
As long as this is enough to use the Color class, you provide a second constructor, a liter, which automatically assigns 255 alpha if not specified by the user.
The third ctr shows that you can create an instance of the Color object with a double value from 0. to 1. instead of integers.
The latter takes color as a unique argument; it copies the given object.
The benefits are also that the first constructor is always called, and you can use it to manually count your instances. Let's say you have a private static int count=0 attribute private static int count=0 , you can track the number of Color instances as follows:
// 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 incremented from any constructor.