我有兩個類這幾乎實現了兩種不同的數值類型相同的操作(除了getHexadecimalValue()
法):組合兩個類似的數字類實現
public class IntegerType
{
private int value;
public IntegerType()
{
value = 0;
}
public void setValue(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
public String getHexadecimalValue()
{
int integerValue = (int) getValue();
String hexadecimal = ValueConversions.toHexadecimal(integerValue);
return hexadecimal;
}
}
和
public class FloatingPointType
{
private float value;
public FloatingPointType()
{
value = 0;
}
public void setValue(float value)
{
this.value = value;
}
public float getValue()
{
return value;
}
public String getHexadecimalValue()
{
float floatingValue = (float) getValue();
int intBits = Float.floatToRawIntBits(floatingValue);
return ValueConversions.toHexadecimal(intBits);
}
}
我我想知道通過如何減少冗餘的最好方法是什麼定義一個超類叫做NumberType
這樣的:
public abstract class NumberType
{
protected Number value;
public NumberType()
{
setValue(0);
}
public void setValue(Number value)
{
this.value = value;
}
public Number getValue()
{
return value;
}
public abstract String getHexadecimalValue();
}
現在的問題是,任何數量的可以傳遞給我的繼承類,但我只希望接受ints
和floats
分別同時仍保持冗餘降到最低:
public class IntegerType extends NumberType
{
@Override
public String getHexadecimalValue()
{
// Crashes on runtime if the value doesn't happen to be of the expected type
int integerValue = (int) getValue();
String hexadecimal = ValueConversions.toHexadecimal(integerValue);
return hexadecimal;
}
}
這可以通過仍然保持適當的類型檢查來完成嗎?
對於浮點數的'toHexString'方法沒有做我想要的,所以我需要我自己的(32位十六進制表示)。是否也可以在超類中對'value'進行0初始化?我想不是,但也許我錯過了一些東西。另請注意,劇組現在是多餘的。謝謝:) – BullyWiiPlaza
我不認爲有可能在超類中進行'0'初始化。但我已經更新了一些代碼。 –