1
0

Types of Inheritance in Java

Inheritance may take different forms:

  • Single inheritance
  • Multilevel inheritance
  • Hierarchical inheritance
  • Multiple inheritance (not directly supported in Java)

Types of inheritance

In the case of single inheritance, only one superclass exists. Whereas in the case of multiple inheritance various superclasses can exist. In the case of hierarchical inheritance, one superclass and various other sub-classes exists, which again can be a superclass for other subclasses. Multilevel inheritance consists of a subclass derived from the superclass, which again becomes a superclass for another subclass, and so on.

It is important to note here that Java does not directly implement multiple inheritances However, this concept is implemented using another form of inheritance i.e. Interfaces (discussed in the next topic). To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. To see how to let’s begin with a short example. The following program creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of class A.

Program to explain the concept of inheritance.

class A // create a super class
{
    int x, y;
    void show1()
    {
        System.out.println("X and Y: "+x+" "+y);
    }
}
class B extends A // Create a sub class by extending class A
{
    int z;
    void show2()
    {
        System.out.println("Z: "+z);
    }
    void sum()
    {
        System.out.println("X+Y+Z: "+(x+y+z));
    }
}
public class SimpleInheritance
{
    public static void main(String args[])
    {
        A super1 = new A(); // object of class A
        B sub1 = new B(); // object of class B
        super1.x = 10; // The super class may be used by itself
        super1.y = 20; // The super class may be used by itself
        System.out.println("Contents of super1: ");
        super1.show1();
        System.out.println();
        sub1.x = 7; // Accessing super class members with subclass object
        sub1.y = 8; 
        sub1.z = 9;
        System.out.println("Contents of sub1: ");
        sub1.show1();
        sub1.show2();
        System.out.println();
        System.out.println("Sum of X, Y, and Z in sub1: ");
        sub1.sum();
    }
}

The output of this program is shown here:

Contents of super1:
X and Y: 10 20
Contents of sub1:
X and Y: 7 8
z: 9
Sum of X, Y and Z in sub1:
X+Y+Z: 24

As you can see, subclass B includes all of the members of its superclass, A. This is why sub1 can access x and y and call show1(). Also, inside sum(), x and y can be referred to directly, as if they were part of B. Even though A is a superclass for B, it is also a completely independent, stand-alone class. Being a superclass for a subclass does not mean that the superclass cannot be used by itself. Further, a subclass can be a superclass for another subclass. The general form of a class declaration that inherits a superclass is shown here:

class subclass-name extends superclass-name
{
    variables declaration;
    methods declaration;
}

You can only specify one superclass for any subclass that you create. Java does not support the inheritance from multiple superclasses into a single subclass. (This differs from C++, in which you can inherit multiple base classes.) You can, as stated, create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass. However, no class can be a superclass in itself.

Program to explain the concept of inheritance.

class Person
{
    String name;
    int age;
    void getdata(String a, int b)
    {
        name=a;
        age=b;
    }
    void show()
    {
        System.out.println("Name = "+name);
        System.out.println("Age = "+age);
    }
}
class Teacher extends Person
{
    float sal;
    void getsal(float a)
    {
        sal=a;
    }
    void display()
    {
        System.out.println("Name of the teacher="+name);
        System.out.println("Age of the teacher="+age);
        System.out.println("Salary of the teacher="+sal);
    }
}
class TestInheritance
{
    public static void main(String s[])
    {
        Teacher tech=new Teacher();
        tech.getdata("Anshuman",30);
        tech.getsal(12000.00f);
        tech.show();
        tech.display();
    }
}

The output from this program is shown here:

Name = Anshuman
Age = 30
Name of the teacher=Anshuman
Age of the teacher=30
Salary of the teacher=12000.0

As you can see, the subclass Teacher includes all of the members of its super class Person. This is why tech can access age, name, and getdata() and call show(). Also, inside display(), age and name can be referred to directly, as if they were part of Teacher. Even though Person is a super class for Teacher, it is also a completely independent, stand-alone class. In the above program Teacher class can also access its data members and member methods too i.e. sal and display().

Member Access and Inheritance

Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private. For example, consider the following simple class hierarchy:

/* In a class hierarchy, private members remain private to their class. This program contains an error and will not compile. */

class A     // Create a superclass
{
    int p;      // public by defalut
    private int q;  // private to A
    void setvalue(int x, int y)
    {
        p=x;
        q=y;
    }
}
class B extends A       // A's q is not accessible here.
{
    int total;
    void sum()
    {
        total=p+q;      // Error, q is not accessible here
    }
}

This program will not compile because the reference to q inside the sum() method of B causes an access violation. Since q is declared as private, it is only accessible by other members of its own class. Subclasses have no access to it.

A class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including subclasses.

Multilevel Inheritance

Up to this point, we have been using simple class hierarchies that consist of only a superclass and a subclass. However, you can build hierarchies that contain as many layers of inheritance as you like. As mentioned, it is perfectly acceptable to use a subclass as a superclass of another. For example, given three classes called A, B, and C, C can be a 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 aspects of B and A. In multilevel inheritance subclass of a superclass act as superclass of another class. Let’s implement the following class hierarchy. Person->Teacher->GuestTeacher. Where guest teacher is paid on lecture basic. In this example Teacher class is a subclass of Person and superclass of GuestTeacher.

Program to implement multilevel Inheritance

class Person
{
    String name;
    int age;
    void getdata(String a, int b)
    {
        name=a;
        age=b;
    }
    void show()
    {
        System.out.println("Name = "+name);
        System.out.println("Age = "+age);
    }
}
class Teacher extends Person
{
    String qual;
    float sal;
    void getqual(String s)
    {
        qual=s;
    }
    void getsal(float a)
    {
        sal=a;
    }
    void display()
    {
        System.out.println("Name of the teacher = "+name);
        System.out.println("Age of the teacher = "+age);
        System.out.println("Qualification of the teacher = "+qual);
        System.out.println("Salary of the teacher = "+sal);
    }
}
class GuestTeacher extends Teacher
{
    float ppl;
    void getppl(float a)
    {
        ppl=a;
    }
    void display()
    {
        System.out.println("Name of the teacher = "+name);
        System.out.println("Age of the teacher = "+age);
        System.out.println("Qualification of the teacher = "+qual);
        System.out.println("Payment per lecture = "+ppl);
    }
}
class TestInheritance1
{
    public static void main(String s[])
    {
        Teacher tech=new Teacher();
        GuestTeacher gt=new GuestTeacher();
        tech.getdata("Anshuman", 30);
        tech.getqual("MSc");
        tech.getsal(12000.00f);
        tech.display();     // diplay() of Teacher class
        gt.getdata("Dr. Chirag", 50);
        gt.getqual("phD");
        gt.getppl(800.00f);
        gt.display();       // display() of GuestTeacher class
    }
}
Name of the teacher = Anshuman
Age of the teacher = 30
Qualification of the teacher = MSc
Salary of the teacher = 12000.0
Name of the teacher = Dr. Chirag
Age of the teacher = 50
Qualification of the teacher = phD
Payment per lecture = 800.0

Teacher class inherits all of the characteristics of Person class and adds new members as qual and sal to them. The Guest Teacher class retains name, age and qual of Teacher class and adds ppl component to it. Also GuestTeacher class redefines the display() method by making suitable modifications. A major advantage of inheritance is that once you have created a superclass that defines the attributes common to a set of objects, it can be used to create any number of more specific subclasses. Each subclass can precisely tailor its own specifications.

Remember, once you have created a superclass that defines the general aspects of an object, that superclass can be inherited to form specialized classes. Each subclass simply adds its own, unique attributes. This is the essence of inheritance.

Hierarchical Inheritance

To see how a multilevel hierarchy can be useful, consider the following program. In it, the superclass Staff is used to create the subclasses called Teacher and Typist. The class Staff contains the common properties of staff member i.e code and name. The subclass Typist adds speed property and subclass Teacher adds subject and qual where code and name are inherited from Staff class.

Program: Write a program to implement Hierarchical inheritance.

class Staff
{
    int code;
    String name;
    Staff()
    {
        code=0;
        name=null;
    }
    Staff(int c, String s)
    {
        code=c;
        name=s;
    }
    void show()
    {
        System.out.println("Code = "+code);
        System.out.println("Name = "+name);
    }
}
class Typist extends Staff
{
    int speed;
    Typist()
    {
        super();
        speed=0;
    }
    Typist(int c, String n, int s)
    {
        super(c,n);
        speed=s;
    }
    void show()
    {
        super.show();
        System.out.println("Speed = "+speed);
    }
}
class Teacher extends Staff
{
    String subject;
    String qual;
    Teacher()
    {
        super();
        subject=null;
        qual=null;
    }
    Teacher(int c, String n, String s, String q)
    {
        super(c,n);
        subject=s;
        qual=q;
    }
    void show()
    {
        super.show();
        System.out.println("Subject = "+subject);
        System.out.println("Qualification = "+qual);
    }
}
class MainInh
{
    public static void main(String args[])
    {
        Staff st=new Staff(12, "Aman");
        Teacher tch=new Teacher(10, "Raman", "Computer", "MCA");
        Typist typ=new Typist(11, "Mahesh", 40);
        Regular reg=new Regular(15, "Dinesh", 50, 12000.00f);
        System.out.println("Staff information......");
        st.show();
        System.out.println("Teacher information......");
        tch.show();
        System.out.println("Typist information......");
        typ.show();
        System.out.println("Regular Typist information......");
        reg.show();
    }
}

This program generates the following output:

Staff information......
Code=12
Name=Aman
Teacher information......
Code=10;
Name=Rama
Subject=Computer
Qualification=MCA
Typist information......
Code=11
Name=Mahesh
Speed=40
Regular Typist information.......
Code=15
Name=Dinesh
Speed=50
Salary=12000.0

In the preceding program, the entire class hierarchy, including Staff, Typist, and Teacher is shown all in one file. This is for your convenience only. In Java, all three classes could have been placed into their own files and compiled separately. In fact, using separate files is the norm, not the exception, in creating class hierarchies.

Note: The public classes should be saved in separate files with the same name as that of the class, as Java does not allow two or more public classes in a single file.

Leave a Reply