FIGURE 8.2: Class inheritance example.
The inheritance relationship is also referred to as an is-a relationship. For example,
a superhero is-a fictional character. The subclass inherits all the attributes and method
of the superclass.
In Java, the extends keywords is used to denote inheritance. Note that both Superhero
and Villain extend from FictionalCharacter .The FictionalCharacter class is the
superclass , while the Superhero and Villain classes are the subclasses .
The new design helped us avoid defining the variable name and the setName and getName
methods multiple times. Note that inside the Superhero class we do not have direct access to
the name of the superhero. The reason is that the variable name is private and therefore it is
only accessible from within the FictionalCharacter class. However, inside the Superhero
class we have access to the FictionalCharacter by using the super keyword. The super
keyword is similar to the this keyword. However, instead of giving us access to the current
object, it gives us access to the super object (i.e., the object of the superclass). For example,
if we put the following code inside a method of the Superhero class, it will print the name
of the superhero.
System. out . println ( super .getName());
Class inheritance is similar to class containment. If the Superhero class inherits from
the FictionalCharacter class, then every object of type Superhero will have an object
of type FictionalCharacter inside it. Figure 8.3 shows an example object for Superman.
As a superhero, he has values for goodPower and respect . In other words, we could have
defined the Superhero classasfollows.
public class Superhero
private int goodPower ;
private int respect ;
private FictionalCharacter superObject ;
Since a Superhero is a type of FictionalCharacter and a Superhero does not have a
FictionalCharacter inside it, the first design is obviously better. After all, we want our
design to follow the scenario that we are modeling as closely as possible.