Multilevel Hierarchy

It is possible to inherit the subclass also like if A is the super class of B then B is the super class of C thus C can access both members of A and B.

//example for multilevel hierarchy
class Item
{
  private String item_name;
  private int item_number;
 protected double item_cost;
  Item(String itname, int itnum, double itcost)
  {
     item_name =itname;
     item_number = itnum ;
     item_cost =itcost ;
  }
  Item()
  {
    item_name = null;
    item_number =-1;
    item_cost =-1;
  }

}
class Market extends Item
{
  private String market_name;
  private int number_of_items;

  Market(String iname, int inum, double icost, String mname,int noi)
  {
    super(iname,inum,icost);
    market_name = mname;
    number_of_items = noi;
  }
  Market()
  {
    super();
    market_name=null;
    number_of_items = -1;
  }
  double itemsCost()
  {
    return number_of_items *(item_cost);
  }


}


class Shipment extends Market
{
  protected double shipping_cost;

  Shipment(String itename, int itenum, double itecost, String maname,int mnoi,double shcost)
  {
    super(itename,itenum,itecost,maname,mnoi);
      shipping_cost = shcost;
  }
  double shippingCost()
  {
    return itemsCost() * shipping_cost;
  }
}

public class MultiLevelDemo
{
  public static void main(String args[])
  {
    Shipment shipment_ob = new Shipment("bottle",123,35.0,"ABC",12,2.0);

    System.out.println("Items Cost is::"+ shipment_ob.itemsCost());
     System.out.println("Shipment Cost is::"+ shipment_ob.shippingCost());                  
  }

}

Output

Items Cost is::420.0

Shipment Cost is::840.0

Constructors Execution

The order of execution of constructor is the order of derivation means from super class to subclass.

As super() is the first statement executes in subclass so that order will be same whether it is not used.

//example to explain constructor execution 
class A 
{
 A() 
 {
 System.out.println("Inside A's constructor.");
 }
}

// Create a subclass by extending class A.
class B extends A 
{
 B() 
 {
 System.out.println("Inside B's constructor.");
 }
}

// Create another subclass by extending B.
class C extends B 
{
 C() 
 {
 System.out.println("Inside C's constructor.");
 }
}


public class CallingCons {
 public static void main(String args[]) {
 C c = new C();
 }
}

Output:

Inside A's constructor.
Inside B's constructor.
Inside C's constructor.

Because the super class doesn't know about subclass what members it want that's why it will initialize it's members first for subclass.

results matching ""

    No results matching ""