【发布时间】:2014-03-09 01:25:59
【问题描述】:
Numbers a,b;
a = new NumbersType(1);
b = new NumbersType(1);
System.out.println(a.equals(b));
public class NumbersType implements Numbers {
int intType;
public NumbersType (int q) {
this.intType = q;
}
public boolean equals(Numbers n) {
return this == n;
}
}
public interface Numbers {
public boolean equals(Numbers n);
}
尽管两个对象是同一个东西,但这会打印错误。将 return this == n 更改为 return this.intType == n.intType 会产生错误“找不到符号:变量 intType,位置:数字类型的变量 n”。
我对 ADT 还很陌生,并且仍在努力解决它,如果这是一个简单的问题,请原谅。但是,我不确定为什么它不起作用,以及为什么我不能引用 n.intType 但我可以 this.intType。
【问题讨论】:
-
始终将
equals实现为equals(Object)。不要给它另一个参数类型。这不是直接的问题,但会导致其他令人讨厌的问题。 -
@user2357112,
Numbers是一个对象。 -
没关系。如果你给你的方法签名
equals(Number),那么Object o1 = someNumber; Object o2 = someOtherNumber; o1.equals(o2);会调用错误的方法。