Multilevel class Hierarchy
- We can build hierarchies that contain as many layers of inheritance as we like.
- It is acceptable to use a subclass as a super class of another.
- For example, we have classes called A, B and C. C can be subclass of B, which is a subclass of A. when this type of situation occurs, each subclass inherits all of the traits found in all of its super classes. In this case, C inherits all properties of B and A.
Example:
class Box
{
private double width;
private double height;
private double depth;
Box(Box ob)
{
width=ob.width;
height=ob.height;
depth=ob.depth;
}
Box(double w, double h, double d)
{
width=w;
height=h;
depth=d;
}
Box()
{
width=-1;
height=-1;
depth=-1;
}
Box(double len)
{
width=height=depth=len;
}
Double volume()
{
return width*height*depth;
}
}
class BoxWeight extends Box
{
double weight;
BoxWeight(BoxWeightob)
{
super(ob);
weight=ob.weight;
}
BoxWeight(double w, double h, double d, double m)
{
super (w,h,d);
weight=m;
}
BoxWeight()
{
super();
weight=-1;
}
BoxWeight(double len, double m)
{
super(len);
weight=m;
}
}
class Shipment extends BoxWeight
{
double cost;
Shipment(Shipment ob)
{
super(ob);
cost=ob.cost;
}
Shipment(double w, double h, double d, double m, double c)
{
super(w,h,d,m);
cost=c;
}
Shipment()
{
super();
cost=-1;
}
Shipment(double len, double m, double c)
{
super(len, m);
cost=c;
}
}
class DemoShipment
{
public static void main(String args[])
{
Shipment ship1= new Shipment(10,20,15,10,3.41);
Shipment ship2= new Shipment(2,3,4,0.76,1.28);
Double vol;
vol=ship1.volume();
System.out.println("Volume of ship1 is:"+vol);
System.out.println("Weight of ship 1 is:"+ship1.weight);
System.out.println("Shipping cost: $"+ship1.cost);
System.out.println();
vol=ship2.volume();
System.out.println("Volume of ship1 is:"+vol);
System.out.println("Weight of ship 1 is:"+ship2.weight);
System.out.println("Shipping cost: $"+ship2.cost);
}
}
Output:
Volume of ship1 is: 3000.0
Weight of ship1 is: 10.0
Shipping cost: $3.41
Volume of ship1 is: 24.0
Weight of ship1 is: 0.76
Shipping cost: $1.28
- This example shows that super() always refers to the constructor in the closest super class.
- The super() in shipment calls the constructor in BoxWeight. The super() in BoxWeight calls the constructor in Box.
- In a class hierarchy, if a super class constructor requires parameters, then all sub-classes must pass those parameters.