We first create a new ColorAttr class that extends the Attr class. The ColorAttr class does everything
the Attr class does and adds new behavior. Therefore, the Attr class is the superclass of ColorAttr, and
ColorAttr is a subclass of Attr. The class hierarchy for these classes looks like this, going bottom-up
from subclass to superclass:
The extended ColorAttr class does three primary things:
It provides three constructors: two to mirror its superclass and one to directly accept a
ScreenColor object.
•
It both overrides and overloads the setValue method of its superclass so that it can set the color
object when the value is changed.
•
It provides a new getColor method to return a value that is the color description decoded into a
ScreenColor object.
•
We look at the intricacies of the construction process and the effect of inheritance on the different class
members over the next few sections.
Note the use of the protected access modifier on the decodeColor method. By making this method
protected it can be accessed in the current class or in a subclass but is not externally visible. We look in
detail at what protected access really means on page 93.
Exercise 3.1: Starting with the Vehicle class from the exercises in Chapter 2, create an extended class
called PassengerVehicle to add a capability for counting the number of seats available in the car and the
number currently occupied. Provide a new main method in PassengerVehicle to create a few of these
objects and print them out.
3.2. Constructors in Extended Classes
An object of an extended class contains state variables (fields) that are inherited from the superclass as well as
state variables defined locally within the class. To construct an object of the extended class, you must
correctly initialize both sets of state variables. The extended class's constructor can deal with its own state but
only the superclass knows how to correctly initialize its state such that its contract is honored. The extended
class's constructors must delegate construction of the inherited state by either implicitly or explicitly invoking
a superclass constructor.
A constructor in the extended class can directly invoke one of the superclass's constructors using another kind
of explicit constructor invocation: the superclass constructor invocation, which uses the super construct.
This is shown in the first constructor of the ColorAttr class:
public ColorAttr(String name, Object value) {
super(name, value);
decodeColor();
}