練習問題3.7
ColorAttr.java
public class ColorAttr extends Attr{ private ScreenColor myColor; public ColorAttr(String name, Object value){ super(name, value); decodeColor(); } public ColorAttr(String name){ this(name,"transparent"); } public ColorAttr(String name, ScreenColor value){ super(name, value.toString()); myColor = value; } public Object setValue(Object newValue){ Object retval = super.setValue(newValue); decodeColor(); return retval; } public ScreenColor setVlue(ScreenColor newValue){ super.setValue(newValue.toString()); ScreenColor oldValue = myColor; myColor = newValue; return oldValue; } public ScreenColor getColor(){ return myColor; } protected void decodeColor(){ if(getValue() == null) myColor = null; else myColor = new ScreenColor(getValue()); } public boolean equals(ColorAttr ca){ if(this.getValue().equals(ca.getValue())) return true; else return false; } public int hashCode(){ return getValue().hashCode(); } public static void main(String[] args){ ColorAttr ca = new ColorAttr("test","red"); ColorAttr ca2 = new ColorAttr("test","red"); System.out.println(ca.hashCode()); System.out.println(ca2.hashCode()); System.out.println(ca.equals(ca2)); } }
実行結果
112785
112785
true
Attrクラスは本の通り、ScreenColorクラスはほぼ空のもの(オブジェクト型を引数に取るコンストラクタのみで実装)を作ってやった。