构造函数重载对于模拟默认值或从已经存在的实例(副本)构造对象非常有用
这是一个例子:
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);
}
}
这里,第一个构造函数非常简单。您为颜色指定 R、G、B 和 Alpha 值。
虽然这足以使用 Color 类,但您提供了第二个构造函数 liter,如果用户未指定,它将自动将 255 分配给 alpha。
第三个 ctr 显示您可以使用介于 0. 和 1. 之间的双精度来实例化 Color 对象,而不是整数。
最后一个以 Color 作为唯一参数,它复制给定的对象。
好处还在于第一个构造函数总是被调用,你可以使用它来手动计算你的实例。假设您有一个 private static int count=0 属性,您可以像这样跟踪 Color 实例的数量:
// 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从任何构造函数中递增。