Java Reference
In-Depth Information
How Java implements generic programming using inheritance
n
How Java 5 implements generic programming using generic classes
n
what is inheritance?
4.1
Inheritance is the fundamental object-oriented principle that is used to
reuse code among related classes. Inheritance models the IS-A relation-
ship . In an IS-A relationship, we say the derived class is a (variation of
the) base class. For example, a Circle IS-A Shape and a Car IS-A Vehicle.
However, an Ellipse IS-NOT-A Circle. Inheritance relationships form hier-
archies . For instance, we can extend Car to other classes, since a Foreign-
Car IS-A Car (and pays tariffs) and a DomesticCar IS-A Car (and does not
pay tariffs), and so on.
In an IS-A relation-
ship , we say the
derived class is a
(variation of the)
base class.
Another type of relationship is a HAS-A (or IS-COMPOSED-OF) rela-
tionship . This type of relationship does not possess the properties that would
be natural in an inheritance hierarchy. An example of a HAS-A relationship is
that a car HAS-A steering wheel. HAS-A relationships should not be modeled
by inheritance. Instead, they should use the technique of composition , in
which the components are simply made private data fields.
As we will see in forthcoming chapters, the Java language itself makes
extensive use of inheritance in implementing its class libraries.
In a HAS-A relation-
ship , we say the
derived class has a
(instance of the)
base class. Compo-
sition is used to
model HAS-A
relationships.
4.1.1 creating new classes
Our inheritance discussion will center around an example. Figure 4.1 shows a
typical class. The Person class is used to store information about a person; in
our case we have private data that includes the name, age, address, and phone
number, along with some public methods that can access and perhaps change
this information. We can imagine that in reality, this class is significantly
more complex, storing perhaps 30 data fields with 100 methods.
Now suppose we want to have a Student class or an Employee class or both.
Imagine that a Student is similar to a Person , with the addition of only a few
extra data members and methods. In our simple example, imagine that the
difference is that a Student adds a gpa field and a getGPA accessor. Similarly,
imagine that the Employee has all of the same components as a Person but also
has a salary field and methods to manipulate the salary.
One option in designing these classes is the classic copy-and-paste : We
copy the Person class, change the name of the class and constructors, and then
add the new stuff. This strategy is illustrated in Figure 4.2.
 
 
Search WWH ::




Custom Search