java - 为什么我们在java中将对象类型转换为类类型?
问题描述
我正在尝试覆盖 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
字段。
推荐阅读
- python - 使用二进制选择器的边界优化求和函数 - GEKKO
- python - 具有更改的数据框多列提取
- postgresql - 通过在 docker compose 的 postgres 命令行上传递 archive_command 来设置 WAL 归档
- python - 尽管安装了“六”包,但无法找到适合 Requirement.parse('six>=1.9') 的发行版
- r - 无法使用 ggplot2 查看完整图表(大小问题)
- android - “RenderFlex 溢出”换行文本抖动
- vba - 通过 MS Access VBA 将选定的 Outlook 电子邮件保存为 .msg 文件
- javascript - 如何通过单击按钮切换类?
- r - 错误:无效输入:date_trans 仅适用于 Date 类的对象 // 不确定如何修复
- sql - 如何将多个单元格合并为一个