Turn Desktop View Off
by Dinesh Thakur

In Our Example illustrates Multilevel Inheritance, Here Class B is derived from superclass A which itself acts as a superclass for the subclass C. The class C inherits the members of Class B directly as it is explicitly derived from it, whereas the members of class A are inherited indirectly into class c (via class B). So the class B acts as a direct superclass and A acts as a indirect superclass for class C.

Each parent-child relationship is representing a level. So class A-class B relationship represents the first level of inheritance and class B-c1ass C represents second level of Inheritance. As the above class hierarchy contains two levels of inheritance which thus represents multilevel inheritance. In multilevel inheritance, there is no limit to the number of levels in a class hierarchy.

Now let us consider a program that shows the multi-level inheritance

class person

{
      private String name;
      person(String s)
      {  
            setName(s);
      }
      public void setName(String s)
      {
        name = s;
      }
      public String getName()
      {
        return name;
      }
      public void display()
      {
        System.out.println("Name = " + name);
      }
}
    class Employee extends person
  {  
       private int empid;
       Employee(String sname,int id) //Constructor Method
       {
         super(sname);
         setEmpid(id);
       }
       public void setEmpid(int id)
       {
         empid = id;
       }
       public int getEmpid()
       {
         return empid;
       }
       public void display()
       {
         super.display();
         System.out.println("Empid = " + empid);
       }
   };
    class HourlyEmployee extends Employee
  {
      private double hourlyRate;
      private int hoursWorked;
      HourlyEmployee(String sname,int id,double hr,int hw)
      {     
         super(sname,id);
         hourlyRate = hr;
         hoursWorked = hw;
      }
      public double GetGrosspay()
      {
        return (hourlyRate * hoursWorked);
      }
      public void display()
      {
        super.display();
        System.out.println("Hourly Rate = " + hourlyRate);
        System.out.println("Hours Worked = " + hoursWorked);
        System.out.println("Gross pay = " + GetGrosspay());
      }
  };
    class MultilevelInheritance
 {
      public static void main(String[] args)
      {
         HourlyEmployee emp = new HourlyEmployee("Dinesh Thakur",1,15,1800);
         emp.display();
      }
 }

Multilevel Inheritance in Java Example