Summary
Let
be a property provable of objects of type . Then should be true for objects of type where .
Polymorphism needs to be done carefully as overriding a method can cause the code to fail without implementer changing anything in their code. This cannot be checked by the compiler.
Effectively, a subclass should not break the expectations set by the superclass. If a class
Example
Given a
Restaurant
class and aLunchRestaurant
subclass, and acanMakeReservation
method.If the
canMakeReservation
method returns true at all times, but the overridden method inLunchRestaurant
does not at certain times: we get the case where a test case fails.Restaurant r = new Restaurant(); Restaurant lr = new LunchRestaurant(); r.canMakeReservation(1200) == true // expected behaviour lr.canMakeReservation(1200) == true // fails
Prevent inheritance
To prevent inheritance and/or overriding, consider using the final
modifier.
- Adding a
final
modifier to the class to prevent it from being inherited. - Adding a
final
modifier to the methods to prevent it from being overridden.