Java Class Inheritance |
Written by Mike James | ||||||
Page 5 of 5
Is Inheritance Bad?When object oriented programming was first invented one of its main claims to be a better system of programming was inheritance. It allowed you to reuse code in a way that was much better than copy and paste reuse because inheritance is a "live" connection between classes. For example, if you change the way the Point class is implemented those changes are inherited by the PointColor class. If you used copy and paste to create the PointColor class you would have to remember to edit it with the changes you made to Point. Unfortunately over time programmers discovered that inheritance was a two edged sword. Any changes you make to Point propagate to PointColor and all of the classes that inherit from it or PointColor or any of its child classes. If this works then great. If it doesn't work then a change in the base class i.e. Point could stop derived classes working. As you can imagine the resulting bugs can be difficult to put right. For this and many other reasons inheritance is not though of as the cure all it once was. Today the motto is "prefer composition over inheritance". What this means is that you can often change your view slightly from IS A to HAS A. For example, PointColor IS A Point with a Color but you could also say PointColor HAS A Point and a Color. In this case you would create an instance of Point within the PointColor class - i.e. no inheritance. Creating objects that have other objects as properties is called composition or aggregation and it is a powerful but sometimes problematic technique. These are all advanced topics and we need to return to the theory of using classes and objects later. For the moment concentrate on the practice of creating and using them. Most of the time you will be writing programs that have very shallow class hierarchies i.e. each class inherits from just Object or perhaps one other class. It seems that inheritance is something that is better when used sparingly. I guess the answer to the question "is inheritance bad?" is no, but it can be used in bad ways. To Summarize
Modern Java
|