Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1
Chapter 5 ■ a Java primer: introduCtion to Java ConCepts and prinCiples

Extending a Java Object Structure: Java Inheritance


There is also support in Java for developing different types of enhanced classes (and therefore objects).
This is done by using an OOP technique called inheritance. Inheritance is where more specialized classes
(more uniquely defined objects) can be subclassed using the original superclass; in this case, it would be
Car. The inheritance process is shown in Figure 5-4. Once a class is used for inheritance by “subclassing” it,
it then becomes the superclass. Ultimately, there can be only one superclass at the very top of the chain, but
there can be an unlimited number of subclasses. All of the subclasses inherit the methods and fields from
the superclass. The ultimate example of this in Java is the java.lang.Object superclass (I sometimes call this
the master class), which is used to create all other classes in Java 9.


As an example of inheritance using the Car class, you could “subclass” the Suv class from the Car class,
using the Car class as the superclass. This is done using the Java extends keyword, which extends the Car
class definition, to create an Suv class definition. This Suv class will define only those additional attributes
(constants), states (variables), and behaviors (methods) that apply to an SUV type of Car object, in addition
to extending all attributes (constants), states (variables), and behaviors (methods) that apply to all types of
Car objects. This is the functionality that the Java extends keyword provides for this subclassing (inheritance)
operation, which is one of the more important and useful features for code modularization within the Java 9
OOP language. You can see this modularization visually in Figure 5-4, with additional Car features for each
subclass added in orange. This is a great way to organize your code!
The Suv Car object subclass might have additional .onStarCall() and .turnTowLightOn() methods
defined, in addition to inheriting the usual Car object operation methods, allowing the Car object to shift
gears, accelerate, apply the brakes, and turn the steering wheel.
Similarly, you might also generate a second subclass, called the Sport class, which creates Sport Car
objects. These might include an .activateOverdrive() method to provide faster gearing and maybe an
.openTop() method to put down the convertible roof. To create the subclass using a superclass, you extend


Figure 5-4. The inheritance of a Car object superclass will allow you to create an SUV Car object and a Sport
Car object

Free download pdf