Using inheritance to add methods... Is it Evil :-)???
A book I''ve been reading "Thinking in Java" maintains that it is evil (my snide term) to use inheritance unless you intend to use it functionally thru upcasting to a base class. So use of a Vehicles class is ok if you will have a container of Vehicles that each have their own version of move(), stop(), pickupPassengers(), pickupCargo() etc.
But the author (Bruce Eckel) says that if your inheriting classes add more methods or variables, then its the sign of bad design.
Is this becoming-accepted-truth about good OO practice, or is this guy on the lunatic fringe? I''m trying to improve my coding style, and keep getting different messages from the ''experts''...
Since the dynamic binding of functions is the whole point of inheritance you should probably ask yourself why are you using inheritance if you are not REALLY using it. That said if you are the only one using the code who cares what the hell your code looks like.
I wanrned you! Didn''t I warn you?! That colored chalk was forged by Lucifer himself!
I would say that it is bad design if not there is at least one common method/datafield in your base class that you upcast to and do something with. If not, there is no point in using inheritance.
However, there is nothing wrong with adding new methods and/or data in derived classes. Specialized classes has specialized methods. There is nothing odd in that. If you look at the Java standard library for instance it is done all the time.
I am reading "Thinking in Java" as well, and I know what you are talking about. I think the author means that if you are using inheritance purely for upcasting, then you should not add to the functionality of the base class, because the added functionality could be lost in an upcast.
However, it makes sense to use inheritance to add functionality when you do not want all of your code sitting in one big class. You may not actually need the added methods after upcasting so in those situations it can be very usefult.
If using inheritance to add methods was evil, the only methods we could ever use in new classes would be those defined in Object!!
In some ways I guess this is a Package versus Class question: If you want to group functionality in separate classes, then you stick them in the same package.
The whole point of inheritance, IMHO, is to promote code reuse, you''ve got a common set of functionality that you don''t want to recode for each class which uses it, so you make them all inherit that code... From that point of view you should not inherit, unless you would end up recoding functionality - it''s up to you to design your prog/library for it to work out that way in practice.