Saturday, May 7, 2011

Inheritance

OO programming makes it easy to add functionality to software without rewriting the code one has already
written and tested. 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.
The SportsCar class must also have a constructor; it’s called SportsCar. The constructor for
SportsCar simply uses the constructor for Automobile, the superclass, by using the super key word to
pass the same values for make, model, year, and power to the constructor for the Automobile class.
The only difference between instances of SportsCar and instances of Automobile will be the
behavior provided by the accelerate() method. In the case of an Automobile, the maximum speed will
be 70, but in the case of a SportsCar, the maximum speed will be 150. We say that the subclass SportsCar
overrides the accelerate() method inherited from the superclass Automobile.
Everything else that is true about an Automobile object will be true about a SportsCar object.
All will have instance variables to store make, model, year, horsepower and speed. Creating either a new
Automobile or a new SportsCar will increment the count of Automobiles maintained by the
Automobile class.
We didn’t have to change any of our existing code to enhance our work to treat sports cars differently from
other automobiles!

No comments:

Post a Comment