我有一个Color
看起来像这样的基类。该类被设计为不可变的,因此具有final
修饰符而没有设置器:
public class Color
{
public static Color BLACK = new Color(0, 0, 0);
public static Color RED = new Color(255, 0, 0);
//...
public static Color WHITE = new Color(255, 255, 255);
protected final int _r;
protected final int _g;
protected final int _b;
public Color(int r, int b, int g)
{
_r = normalize(r);
_g = normalize(g);
_b = normalize(b);
}
protected Color()
{
}
protected int normalize(int val)
{
return val & 0xFF;
}
// getters not shown for simplicity
}
派生自这个类的是一个ColorHSL
类,除了提供Color
类的 getter 之外,它还具有色调、饱和度和亮度。这是事情停止工作的地方。
的构造函数ColorHSL
需要做一些计算,然后设置_r
、_b
和的值_g
。但是必须在进行任何计算之前调用超级构造函数。因此引入了无参数构造函数,允许稍后设置Color()
final _r
、_b
和。但是, Java 编译器不接受_g
无参数构造函数或设置(第一次,在 的构造函数中)。ColorHSL
有没有办法解决这个问题,还是我必须从、和中删除final
修饰符?_r
_b
_g
编辑:
Color
最后,我选择了一个包含 RGB 和 HSL 数据的基本抽象类。基类:
public abstract class Color
{
public static Color WHITE = new ColorRGB(255, 255, 255);
public static Color BLACK = new ColorRGB(0, 0, 0);
public static Color RED = new ColorRGB(255, 0, 0);
public static Color GREEN = new ColorRGB(0, 255, 0);
public static Color BLUE = new ColorRGB(0, 0, 255);
public static Color YELLOW = new ColorRGB(255, 255, 0);
public static Color MAGENTA = new ColorRGB(255, 0, 255);
public static Color CYAN = new ColorRGB(0, 255, 255);
public static final class RGBHelper
{
private final int _r;
private final int _g;
private final int _b;
public RGBHelper(int r, int g, int b)
{
_r = r & 0xFF;
_g = g & 0xFF;
_b = b & 0xFF;
}
public int getR()
{
return _r;
}
public int getG()
{
return _g;
}
public int getB()
{
return _b;
}
}
public final static class HSLHelper
{
private final double _hue;
private final double _sat;
private final double _lum;
public HSLHelper(double hue, double sat, double lum)
{
//Calculations unimportant to the question - initialises the class
}
public double getHue()
{
return _hue;
}
public double getSat()
{
return _sat;
}
public double getLum()
{
return _lum;
}
}
protected HSLHelper HSLValues = null;
protected RGBHelper RGBValues = null;
protected static HSLHelper RGBToHSL(RGBHelper rgb)
{
//Calculations unimportant to the question
return new HSLHelper(hue, sat, lum);
}
protected static RGBHelper HSLToRGB(HSLHelper hsl)
{
//Calculations unimportant to the question
return new RGBHelper(r,g,b)
}
public HSLHelper getHSL()
{
if(HSLValues == null)
{
HSLValues = RGBToHSL(RGBValues);
}
return HSLValues;
}
public RGBHelper getRGB()
{
if(RGBValues == null)
{
RGBValues = HSLToRGB(HSLValues);
}
return RGBValues;
}
}
RGBColor
然后HSLColor
派生自的类Color
,实现一个简单的构造函数来初始化RGBValues
和HSLValues
成员。(是的,我知道基类 if-ily 包含派生类的静态实例)
public class ColorRGB extends Color
{
public ColorRGB(int r, int g, int b)
{
RGBValues = new RGBHelper(r,g,b);
}
}
public class ColorHSL extends Color
{
public ColorHSL(double hue, double sat, double lum)
{
HSLValues = new HSLHelper(hue,sat,lum);
}
}