java - Advantages of Constructor Overloading -
i new java , trying learn subject, having previous programming exposure in html/css. have started herbert schildt , progressed through few pages.
i unable understand exact advantages of constructor overloading. isn't easier overload methods using single constructor flexibility? if trying use constructor overloading use 1 object initialize another, there simpler ways it! benefits , in situation should use constructor overloading.
constructor overloading useful simulate default values, or construct object existing instance (copy)
here 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 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, first constructor simple. specify r,g,b & alpha value color.
while enough use color class, provide second constructor, liter, auto assign 255 alpha if not specified user.
the third ctr shows can instantiate color object double between 0. , 1. instead of integers.
the last 1 takes color unique argument, copies given object.
the benefits lies in fact first constructor called, , can use manually count instances. let have private static int count=0
attribute, can track number of color instance 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 constructor.
Comments
Post a Comment