我正在尝试覆盖 equals 方法。 由于某种原因,我们的教授将对象参数转换为类型类(计数器)。
有人可以向我解释一下这背后的逻辑吗?如果我代替“Couter that = (Counter) other;”只需删除该行并将“that.count”更改为“other.count”,它就可以正常执行。
public class Counter {
private int count;
public Counter() {
count = 2;
}
public boolean equals(Counter other) {
if (other instanceof Counter) {
Counter that = (Counter) other;
return (this.count == that.count);
} else {
return false;
}
}
public static void main(String args []) {
Counter casio = new Counter();
Counter texas = new Counter();
System.out.println(casio.equals(texas));
}
}
最佳答案
您的 equals 方法的签名是错误的。为了重写该方法,它需要有一个 Object
类型的参数:
@Override
public boolean equals(Object other) {
这需要您将 other
转换为 Counter
并执行 instanceof
检查,否则您无法访问 count
字段。
关于java - 为什么我们在java中将对象类型转换为类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54948148/