3 ms·
There's several fine replies already. Another aspect to consider is that inheritance is tied up with polymorphism. If your B class inherits from an A class, the
by codebje 7y ago
There's several fine replies already. Another aspect to consider is that inheritance is tied up with polymorphism. If your B class inherits from an A class, then anywhere that an A is expected, a B may be supplied instead.
If another body of code entirely was written and tested using As, without knowing that Bs exist, it may not work if given a B, unless that B happened to perform exactly the same as an A in whatever (unknown, unknowable) ways matter to that other body of code.
An object's interface is its specification. But most objects are woefully underspecified, with types (if you're lucky) and perhaps a bit of prose explaining what it's supposed to do. Preconditions and postconditions are rare, laws and properties are rarer still. Languages that are able to test those things hold are even rarer.
My own recommendation is to inherit only from abstract parents, and if your language supports it, to make any concrete class final. If you need some behaviour to be overridable at time of use, apply the Strategy pattern. There's a cost to this: you need to implement Strategy, and you will not think of all cases where behaviour should be overridable. But the cost of random errors that crop up at run time is IMO likely to be higher.