Rather than building every class from the ground up, Java supports an objectoriented programming concept called inheritance that allows one class to include all the properties and methods of another class. You can also think of this as a parent–child relationship, in which each child acquires the attributes of all its ancestors. It is important to note that Java's implementation of inheritance supports single inheritance only, so each child has a single parent. Figure 26.17 illustrates the code for a SUV class that inherits the properties and methods of the Vehicle class shown in Figure 26.15.
Figure 26.17: Java inheritance.
Figure 26.18 shows the new code for the Buycar application. This time, it creates a single instance of the SUV class, prints its original color and gear, uses the Paint method to change the vehicles color, uses the Shift method to change the gear, and then prints the new color and gear.
Figure 26.18: Java methods.
The following command invokes the Buycar application:
The output is as follows:
Original Color = Silver Original Gear = 2WD New Color = Gold New Gear = 4WD