146 CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces
The Suv subclass might have additional .onStarCall and .turnTowLightOn( ) methods defined, in
addition to inheriting the usual Car object operational (basic car function) methods allowing the Car
object to shift gears, accelerate, apply the brakes, and turn the wheels.
Similarly, we might also generate a second subclass, called the Sport class, which would create
Sport objects. These might include an .activateOverdrive( ) method,to provide faster gearing, and
an .openTop( ) method,to put down the convertible roof.
To create a subclass using a superclass, you extend the subclass from the superclass, by using the
Java extends keyword inside of the class declaration. The Java class construct would thus look just
like this:
class Suv extends Car {
// Additional New Variable Data Fields, Constants, and Methods Will Go In Here.
}
This extends the Car class so that Suv objects have access to, essentially contain, all of the data
fields and methods that the Car object features. This allows the developer to have to focus only on
just the new or different data fields and methods that relate to the differentiation of the Suv object
from the regular or “master” Car object definition.
Since classes create objects, given that they have a constructor method, the same hierarchy could
be applied at the spawned object level. So logically, the Suv object will be more complex (more data
fields and functionality) than a Car object.
To refer to one of the superclass’s methods from within the subclass you are coding, you can use
the Java super keyword. For example, in the new Suv class,you may want to use the master Car
object’s .applyBrake( ) method, and then apply some additional functionality to the brake that is
specific to SUVs. You can call the Car object .applyBrake( ) method by using super.applyBrake( )
in the Java code. The following Java code will add additional functionality to the Car object’s
.applyBrake( ) method, inside of the Suv object’s .applyBrake( ) method, by using the super keyword
to access the Car object’s .applyBrake( ) method, and then adds in additional logic:
class Suv extends Car {
void applyBrake (int brakingFactor) {
super.applyBrake(brakingFactor);
speed = speed - brakingFactor;
}
}
This code makes the Suv object’s brakes twice as powerful as the generic Car object’s brakes,
which is again something that would have to take place in “real life” for an SUV to be safe for
use. The reason this Java code doubles the SUV’s braking power is because the Suv object’s
.applyBrake( ) method first calls the Car object’s .applyBrake( ) method from the Car superclass using
the super.applyBrake(brakingFactor); line of Java code in the Suv subclass .applyBrake( ) method,
and then the line of Java code that comes next (again) decreases the speed variable, by applying the
brakingFactor a second time, making the brakes twice as powerful or effective!