首页 > 解决方案 > 为什么我们在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));
    }
}

标签: javaclassobjectcasting

解决方案


您的 equals 方法的签名是错误的。为了覆盖该方法,它需要有一个类型的参数Object

@Override
public boolean equals(Object other) {

这需要您强制other转换Counter并进行instanceof检查,否则您将无法访问该count字段。


推荐阅读