【发布时间】:2009-11-14 14:31:05
【问题描述】:
我有一个基本的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() 构造函数,允许稍后设置最终的_r、_b 和_g。但是,Java 编译器不接受无参数构造函数或设置(第一次,在ColorHSL 的构造函数中)。
有没有办法解决这个问题,还是我必须从_r、_b 和_g 中删除final 修饰符?
编辑:
最后,我选择了一个基本抽象 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);
}
}
【问题讨论】:
-
顺便说一句,从超类的构造函数调用子类是危险的,以防这些方法依赖于子类尚未初始化的状态,因为它的构造函数在超类的构造函数正在运行。
标签: java inheritance immutability final