我需要编写抽象类,如下所示。
public abstract class Value {
public abstract String toString();
public abstract Value add(Value v);
public abstract Value sub(Value v);
public abstract boolean eq(Value v);
public abstract boolean lte(Value v);
public abstract boolean gte(Value v);
public abstract boolean neq(Value v);
public abstract boolean equals(Object other);
public abstract int hashCode();
public abstract Value create(String s);
}
现在我需要创建几个继承自该类的类。我从 Int 类开始,实现如下:
public class Int extends Value {
int val;
public String toString() {
String toStr = Integer.toString(val);
return toStr;
}
public Int add(Value v) {
Int result = new Int();
if(v instanceof Int) {
Int temp = (Int) v;
result.val = val + temp.val;
}
return result;
}
public Int sub(Value v) {
Int result = new Int();
if(v instanceof Int) {
Int temp = (Int) v;
result.val = val - temp.val;
}
return result;
}
public boolean eq(Value o) {
if(this == o) return true;
if(this == null) return false;
if(getClass() != o.getClass()) return false;
Int other = (Int) o;
return toString() == other.toString();
}
public boolean lte(Value v) {
if(v instanceof Int) {
Int temp = (Int) v;
return this.val < temp.val;
}
return false;
}
public boolean gte(Value v) {
if(v instanceof Int) {
Int temp = (Int) v;
return this.val > temp.val;
}
return false;
}
public boolean neq(Value v) {
if(v instanceof Int) {
Int temp = (Int) v;
return !eq(temp);
}
return true;
}
public boolean equals(Object o) {
if(this == o) return true;
if(this == null) return false;
if(getClass() != o.getClass()) return false;
Int other = (Int) o;
return toString() == other.toString();
}
public int hashCode() {
Integer hash = val;
return hash.hashCode();
}
public Int create(String s) {
val = Integer.parseInt(s);
return this;
}
}
一切都在编译和工作,但我不知道我的 hashcode() 函数和 equals() 是否良好。此外,我想使用 create() 来制作这样的对象:
getInstance().create("1234");
我的方法也足够了吗?
最佳答案
Everything is compiling and working, but I have no clue if my hashcode() function and equals() are good.
您的equals()
应该比较int val
而不是比较对象的toString()
结果(this.val = = other.val
)。
你的hashCode()
看起来不错,尽管我会添加@Override
(与equals()
相同)。
Furthermore i want to use create() to make objects like this:
getInstance().create("1234");
看看它的实现,它看起来不错(即可以根据您的需要工作):
public Int create(String s) {
val = Integer.parseInt(s);
return this;
}
尽管我不认为您真的想将它与 getInstance()
一起使用。简单地 Int.create()
就足够了:
public static Int create(String s) {
val = Integer.parseInt(s);
return new Int(val);
}
请注意,您需要一个私有(private)构造函数。
此外,正如有人在评论中指出的那样,请考虑使用泛型而不是继承。
关于java - Java抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52843089/