This characteristic of OO programming is called polymorphism,
and it is a powerful feature of the OO approach.
We will add some lines to our AutomobileFactory class to set the speed of a family car to 120 and
set the speed of a sports car to 120. Looking back at the accelerate() method for the class Automobile,
you will see that the maximum speed for an instance of the Automobile class is 70. Compare that with the
accelerate() method for the SportsCar class; the top speed for a SportsCar is 150.
When we call the same accelerate() method for an instance of Automobile and an instance of
SportsCar, the results are different. The Automobile speeds up to 70, and the SportsCar speeds up to
120. To show this, add code to the AutomobileFactory class:
/**
* Class AutomobileFactory
* @author Carl Reynolds
*/
class AutomobileFactory {
.
.
.
family = new Automobile(
"VW", "Passat", 2002, 170 );
sports = new SportsCar(
"Ford", "Mustang", 2005, 300 );
.
.
.
//same method call to instances of 2 different classes
family.accelerate(120. );
sports.accelerate(120. );
//polymorphism will cause the effects to be different
System.out.println( family + " " + family.getSpeed() );
System.out.println( sports + " " + sports.
Pages:
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227