Reputation: 151
I'm learning Java and am having some trouble with casting/polymorphism concepts.
If I have the following method:
public boolean equals(Object x);
Where x could reference an Object of Class Y;
What's the best way to see if x equals y (a variable referencing an obj of Class Y) ? I understand downcasting e.g. (Y) x is bad?
Upvotes: 0
Views: 101
Reputation: 1
It highly depends on your interpretation of equality. That's why the equals operator can be overridden.
Just do x.equals(y)
and do the interpretation of equality by overriding the equals method.
One template method for this is to do:
public boolean equals(Object x) {
if (this == x)
return true;
if (x == null || this.getClass() != x.getClass())
return false;
// Compare attributes as needed here
}
Of course you should check if x != null
before, if there are chances it is null
.
Upvotes: 0
Reputation: 200206
Downcasting is the norm in Object.equals
. Before downcasting, check that x
is indeed a compliant object with x instanceof Y
; to ensure the symmetry of equals
, a check x.getClass() == this.getClass()
will be necessary at times.
If x
is not an instance of your class, you immediately return false
.
Upvotes: 3
Reputation: 48434
Downcasting is not bad if you firstly perform the following checks:
x != null
getClass().equals(x.getClass())
Then you can downcast x
as the class of this
, and perform specific comparisons.
Prior to your null
check, you may also want to compare references of this
and x
.
If the references are equal, you don't need to perform any other comparison.
Upvotes: 1