You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在equals方法中访问其他对象属性为何报错?如何正确访问?

重写equals方法时访问属性报错的原因

错误代码

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

报错信息:valorHash cannot be resolved or is not a field(注:推测是变量名拼写/翻译差异,代码中实际为hashValue)

可行代码

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是静态类型语言,编译器检查代码合法性时,只认变量的编译时声明类型,不管它运行时实际是什么类型。

  • 错误代码里,other的声明类型是Object,而Object类本身并没有hashValue这个属性。哪怕你用instanceof判断出它运行时是Termino实例,这也只是运行时的逻辑判断,编译阶段编译器不会因为这个判断就自动把other的类型升级为Termino,所以直接访问other.hashValue会被判定为非法。
  • 可行代码里,你把other显式强转为Termino类型并赋值给aux,此时aux的编译时类型是Termino,编译器能识别到这个类定义了hashValue属性,因此可以正常访问。

一句话总结:instanceof是运行时的类型校验,编译阶段要访问子类特有的成员,必须先显式强转类型。

内容的提问来源于stack exchange,提问作者Ardust

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 10:19:59