Java Reference
In-Depth Information
Because classesareinvolved,Javareferstothiskindofinheritance as implementation
inheritance .
Javasupportsmultipleinheritanceonlyinaninterfacecontext,inwhichaclassinher-
itsbehaviortemplatesfromoneormoreinterfacesthroughinterfaceimplementation,or
in which an interface inherits behavior templates from one or more interfaces through
interfaceextension.Becauseinterfacesareinvolved,Javareferstothiskindofinherit-
ance as interface inheritance . (I discuss interfaces later in this chapter.)
ThissectionintroducesyoutoJava'ssupportforimplementationinheritancebyfirst
focusingonclassextension.Itthenintroducesyoutoaspecialclassthatsitsatthetopof
Java'sclasshierarchy.Afterintroducingyoutocomposition,whichisanalternativeto
implementation inheritance for reusing code, this section shows you how composition
can be used to overcome problems with implementation inheritance.
Extending Classes
Java provides the reserved word extends for specifying a hierarchical relationship
betweentwoclasses.Forexample,supposeyouhavea Vehicle classandwanttoin-
troduce Car and Truck classesthatextend Vehicle . Listing2-21 uses extends to
cement these relationships.
Listing 2-21. Relating classes via extends
class Vehicle
{
// member declarations
}
class Car extends Vehicle
{
// member declarations
}
class Truck extends Vehicle
{
// Member declarations
}
Listing 2-21 codifies relationships that are known as “is-a” relationships: a car or a
truck is a kind of vehicle. In this relationship, Vehicle is known as the base class ,
 
Search WWH ::




Custom Search