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
Restaurantclass and aLunchRestaurantsubclass, and acanMakeReservationmethod.If the
canMakeReservationmethod returns true at all times, but the overridden method inLunchRestaurantdoes 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
finalmodifier to the class to prevent it from being inherited. - Adding a
finalmodifier to the methods to prevent it from being overridden.