TheFreeSite.com!

Monday, July 28, 2008

Inheritance:reusing the interface

By itself, the concept of an object is a convenient tool. It allows you to package data and
functionality together by concept, so you can represent an appropriate problem-space idea
rather than being forced to use the idioms of the underlying machine. These concepts are
expressed in the primary idea of the programming language as a data type (using the class
keyword).
It seems a pity, however, to go to all the trouble to create a data type and then be forced to
create a brand new one that might have similar functionality. It’s nicer if we can take the
existing data type, clone it and make additions and modifications to the clone. This is
effectively what you get with inheritance, with the exception that if the original class (called
the base or super or parent class) is changed, the modified “clone” (called the derived or
inherited or sub or child class) also reflects the appropriate changes. Inheritance is
implemented in Java with the extends keyword. You make a new class and you say that it
extends an existing class.
When you inherit you create a new type, and the new type contains not only all the
members of the existing type (although the private ones are hidden away and inaccessible),
but more importantly it duplicates the interface of the base class. That is, all the messages
you can send to objects of the base class you can also send to objects of the derived class.
Since we know the type of a class by the messages we can send to it, this means that the
derived class is the same type as the base class. This type equivalence via inheritance is one of
the fundamental gateways in understanding the meaning of object-oriented programming.
Since both the base class and derived class have the same interface, there must be some
implementation to go along with that interface. That is, there must be a method to execute
Chapter 1: Introduction to Objects 47
when an object receives a particular message. If you simply inherit a class and don’t do
anything else, the methods from the base-class interface come right along into the derived
class. That means objects of the derived class have not only the same type, they also have the
same behavior, which doesn’t seem particularly interesting.
You have two ways to differentiate your new derived class from the original base class it
inherits from. The first is quite straightforward: you simply add brand new functions to the
derived class. These new functions are not part of the base class interface. This means that
the base class simply didn’t do as much as you wanted it to, so you add more functions. This
simple and primitive use for inheritance is, at times, the perfect solution to your problem.
However, you should look closely for the possibility that your base class might need these
additional functions.

0 comments:

Tell Me Doubts In Java