0
$\begingroup$

From http://web.mit.edu/6.031/www/fa19/classes/12-interfaces-enums/#implementing_generic_interfaces

"That means B is only a subtype of A if B’s specification is at least as strong as A’s specification. When we declare a class that implements an interface, the Java compiler enforces part of this requirement automatically: for example, it ensures that every method in A appears in B, with a compatible type signature. Class B cannot implement interface A without implementing all of the methods declared in A.

But the compiler cannot check that we haven’t weakened the specification in other ways: strengthening the precondition on some inputs to a method, weakening a postcondition, weakening a guarantee that the interface abstract type advertises to clients. If you declare a subtype in Java — implementing an interface is our current focus — then you must ensure that the subtype’s spec is at least as strong as the supertype’s."

However, later they define a generic class Set with method contains(E e) and a non-generic subclass CharSet with method contains(Character e). Does this count as strengthening pre-condition? If so, does it contradict the above?

$\endgroup$
0
$\begingroup$

CharSet is not a subtype of Set<E>, but it is a subtype of Set<Character>. If you compare the signatures of the contains methods for Set<Character> and CharSet, you'll see that the preconditions are identical.

It might be helpful to imagine that Set is not a type and is not meaningful on its own; you have to instantiate the generic parameter to obtain a type.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.