Inheritance The easiest way to explain something new is to start with something old. If you want to describe what a ``schooner'' is, it helps if your listeners already know what ``sailboat'' means. If you want to explain how a harpsichord works, it's best if you can assume your audience has already looked inside a piano, or has seen a guitar played, or at least is familiar with the idea of a ``musical instrument.'' The same is true if want to define a new kind of object; the description is simpler if it can start from the definition of an existing object. With this in mind, object-oriented programming languages permit you to base a new class definition on a class already defined. The base class is called a superclass; the new class is its subclass. The subclass definition specifies only how it differs from the superclass; everything else is taken to be the same. Nothing is copied from superclass to subclass. Instead, the two classes are connected so that the subclass inherits all the methods and instance variables of its superclass, much as you want your listener's understanding of ``schooner'' to inherit what they already know about sailboats. If the subclass definition were empty (if it didn't define any instance variables or methods of its own), the two classes would be identical (except for their names) and share the same definition. It would be like explaining what a ``fiddle'' is by saying that it's exactly the same as a ``violin.'' However, the reason for declaring a subclass isn't to generate synonyms, but to create something at least a little different from its superclass. You'd want to let the fiddle play bluegrass in addition to classical music.
Why Use Inheritance?
Inheritance is a large part of the reason that Object Oriented Programming is a powerful tool. It has the following advantages:
you can customize and enhance working classes
it is easier to reuse code
you can take a more general class and modify to suit a particular situat
Sunday, September 28, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment