如何在equals方法中访问其他对象的属性?

问题描述 投票:0回答:1

我正在尝试用以下代码覆盖

equals
方法:

public boolean equals(Object other) {
        if(!(other instanceof Termino)) return false;
        if(this.hashValue == other.hashValue) return true;
        return false;
}

据我所知,如果

instanceof
true
类的对象,
other
会返回
Termino
,所以
other
会有一个名为
hashValue
的属性,但我得到了错误
valorHash cannot be resolved or is not a field
。为什么?

我的有效解决方案是:

public boolean equals(Object other) {
        if(!(other instanceof Termino)) return false;
        Termino aux = (Termino) other;
        if(this.hashValue == aux.hashValue) return true;
        return false;
}

但我不明白为什么我的第一次尝试是错误的。

java object equals bluej
1个回答
0
投票

如果您尝试使用第一种方法访问对象的属性,它将不起作用,因为它会在“Object”类上查找 hashValue。当您转换它时,您允许它访问 Termino 类的属性。

© www.soinside.com 2019 - 2024. All rights reserved.