Advantages of Constructor Overloading

前端 未结 6 1820
青春惊慌失措
青春惊慌失措 2021-01-18 10:45

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 fe

6条回答
  •  滥情空心
    2021-01-18 11:42

    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;
        }
    

    countis incremented from any constructor.

提交回复
热议问题