I am trying to implement an public boolean equals(Object other)
method for my Java class where the first argument is passed as an Object type. The problem is that I do not know how to access to the attributes of an Object type.
Asked
Active
Viewed 589 times
0

anonon
- 31
- 1
-
Does this answer your question? [How to override equals method in Java](https://stackoverflow.com/questions/8180430/how-to-override-equals-method-in-java) – moonman4 Dec 07 '21 at 17:41
1 Answers
0
Object a very general class and will likely be of little use to you on its own.
If you are trying to access properties of some other class then you need to check the Object other
is an instance of YourClass
and then cast it.
[enter link description here][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

moonman4
- 308
- 3
- 12