You need to :
- Assign the result of the cast to your class reference type so that the compiler is able to find the
getOperand
method since Object
class doesn't have such a method.
- Use the
equals
method to compare the operand
values rather than using ==
.
- Use
instanceof
so that the solution supports mixed type equality. (Read Liskov Substitution Principle. Optional if you don't want to support mixed type equality)
Mark the equals
method as final
to prevent subclasses from overriding it inorder to support symmetry (if x.equals(y)
then y.equals(x)
. Not required if not supporting mixed type equality)
public abstract class EqualsTest {
public final boolean equals(Object o) {//make equals final to maintain symmetry
if (o instanceof EqualsTest) {//use instanceof
EqualsTest e = (EqualsTest)o;//cast and assign to EqualTest reference
return e.getOperand().equals(this.getOperand());//use equals here
} else
return false;
}
}
}
With the above changes, sub-classes can inherit the equals method as is :
class EqualsTestSubClass extends EqualsTest {
//inherts the equals and getOperand methods.
}
class EqualsTestSubClass2 extends EqualsTestSubClass {
//inherts the equals and getOperand methods.
}
You can then check equality of an EqualsTestSubClass
instance which is a direct subclass of EqualsTest
and EqualsTestSubClass2
instance which is a subclass of EqualsTestSubClass
instances as follows :
EqualsTest e1 = new EqualsTestSubClass();
EqualsTest e2 = new EqualsTestSubClass2();
System.out.println(e1.equals(e2));
Note : It is a better idea to directly compare the operand
field in the equals
method rather than using getOperand
since getOperand
is overridable.