Multilevel & Multiple Inheritance

 

  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.

 

Multiple Inheritance

     Some object oriented languages, notably C++, allow a class to inherit from more than one unrelated class. This is 

called multiple inheritance and is different from the multi-level inheritance in this section. Most of the things that can 

be accomplished via multiple inheritance in C++ can be handled by interfaces in Java

 

List | Previous | Next