If I have a complex hierachy of inheritance and I want to do an equality check that depends on a specific equality is there a way to ensure I run using that equality check and not a version overridden by a child class that may behave different then I want?
To give an example lets say I have a foo with it's own equality class, and then I have something like boo with an equals class sort of like below sudocode (too lazy to right it out in full)
class Foo {
int id;
int otherId;
int count;
public boolean equals(Object other){
//check other instance of foo and re-cast
return (id==other.id && otherId==other.otherId)
}
}
class Bar extends Foo{
private someObject uniqueValue;
public boolean equals(Object other){
//check other instance of foo and re-cast
return super.equals(other) && other.getUniqueValue.equals(this.getUniqueValue);
{
}
Then I have some method which takes too foo objects which reference the same foo and add up the counts for them
public combineFoos(Foo foo1, Foo foo2){
if(! foo1.equals(foo2))
throw IllegalArgumentException("no match");
Foo combinedFoo=new Foo(foo1.id, foo1.otherId, (foo1.count + foo2.count))
return combinedFoo
}
}
In theory this all works, until the bar value comes in. Now if I call combineFoo and pass in a bar to foo1 it fails, because bars equal method checks foo2 is an instanceOf bar. I really don't care if foo2 is a bar, the information I need is available for any foo. For that matter if I pass in two unequal bars that both are equal as defined by foo's equality method (ie only the uniqueValue fields are different) I would want the combineFoo to still accept them as equal Foo's, even if not equal by Bar's definition.
The problem is that I want to do an equality check on exactly what a FOO considers as equal, but I don't know what bizarre inherited class I may actually receive. Is there a way to work around this, to basically say in my combineFoo to always use a FOOs definition of equals, even if it is overridden by a child class?
Related, would this be a far worse idea then I imagine it be even if doable, or is there some other way to handle something like the above example, short of effectively re-writing foo's equal method within the combineFoo?