【发布时间】:2022-01-12 18:41:49
【问题描述】:
我正在尝试为我的 Java 类实现 public boolean equals(Object other) 方法,其中第一个参数作为 Object 类型传递。问题是我不知道如何访问 Object 类型的属性。
【问题讨论】:
-
这能回答你的问题吗? How to override equals method in Java
我正在尝试为我的 Java 类实现 public boolean equals(Object other) 方法,其中第一个参数作为 Object 类型传递。问题是我不知道如何访问 Object 类型的属性。
【问题讨论】:
Object 是一个非常通用的类,单独使用可能对您没有什么用处。
如果您尝试访问其他类的属性,则需要检查 Object other 是 YourClass 的实例,然后对其进行转换。
[在此处输入链接描述][1]
class yourClass {
@Override
public boolean equals(Object other) {
// nothing to compare if other is null
if(other == null) return false;
// Can only be equals if they are both YourClass
if(other instanceof YourClass){
// Tell java to make other into YourClass instead of Object
YourClass yourClass = (YourClass)other
//Access properties of another here
//...
}
// other is not an instance of YourClass so it cant be equals
return false;
}
[1]: https://stackoverflow.com/questions/8180430/how-to-override-equals-method-in-java
【讨论】: