I was wondering how best to implement equals () for a family of classes that implement the same interface (and the client should only work with the specified interface and never know about the implementation of the classes).
I have not prepared my own specific example, but there are two examples in the JDK - java.lang.Number and java.lang.CharSequence, which illustrate the solution:
boolean b1 = new Byte(0).equals( new Integer(0) ) );
or with CharSequence
boolean b2 = "".equals(new StringBuilder());
Do you ideally want those who value this to be true or not? Both types implement the same data type interface, and as a client working with Numbers instances (CharSequences respectively), it would be easier for me if equals compared interface types instead of implementation types.
Now this is not a perfect example, since the JDK reveals implementation types to the public, but suppose that we do not need to maintain compatibility with what already exists, from the point of view of designers: it should be checked for compliance with the interface or better, the way it is checking implementation?
Note. I understand that checking for equality with respect to an interface can be very difficult to actually implement in practice, and make it even more complex, since equal interfaces must also return the same hashCode (). But these are only obstacles in the implementation, for example, CharSequence, although the interface is quite small, everything that is required for equality checks is present without revealing the internal structure of the implementation (therefore, it is fundamentally possible to correctly implement it, without even knowing about the future implementation in advance). But I'm more interested in design, not how to implement it. I would not decide, based only on how difficult it is to implement something.
java equals design interface
Durandal
source share