Multilevel Inheritance
The Car-Motorcycle-MotorVehicle example showed single-level inheritance. There's nothing to stop you from going further. You can define subclasses of cars for compacts, station wagons, sports coupes and more.
For example, this class defines a compact as a car with two doors:
public class Compact extends Car {
// constructors
public Compact(String licensePlate, double maxSpeed,
String make, String model, int year, int numberOfPassengers) {
this(licensePlate, 0.0, maxSpeed, make, model, year, numberOfPassengers);
}
public Compact(String licensePlate, double speed, double maxSpeed,
String make, String model, int year, int numberOfPassengers) {
super(licensePlate, speed, maxSpeed, make, model,
year, numberOfPassengers, 2);
}
}
Compact not only inherits from its immediate superclass,
Car, but also from Car's superclass, MotorVehicle. Thus the Compact class also has a make, a model, a year and so on. There's no limit to this chain of inheritance, though getting more than four or five classes deep makes code excessively complex.
Previous | Next | Top
Last Modified June 16, 1999
Copyright 1997, 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu