Suppose we want to add distinctions between types of Automobiles. A Ferrari can go
much faster than a Kia, so the accelerate() method should be different, and perhaps other behaviors
should also be different for such different Automobiles.
We can add a new class called SportsCar that will inherit from Automobile, and we can give the
SportsCar class a different accelerate() method. Here is the Java class for SportsCar:
/**
* Class SportsCar
* Inherits from class Automobile
* @author Carl Reynolds
*/
class SportsCar extends Automobile {
private double maxSpeed = 150.;
//constructor
SportsCar( String mk, String mdl, int yr, int power )
{
super( mk, mdl, yr, power );
}
//override of inherited accelerate() method
public void accelerate( double newSpeed )
{
if( newSpeed > maxSpeed ) speed = maxSpeed;
else speed = newSpeed;
}
}
The SportsCar class extends the class Automobile; that means SportsCar inherits from
Automobile. Any instance of a SportsCar will also be an Automobile, and except where there are
differences between the code for SportsCar and the code for Automobile, an instance of a SportsCar
will have exactly the same state variables and behavior as any instance of the class Automobile.
Pages:
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225