Multiple inheritance using interfaces in Java

In object-oriented programming, multiple inheritance is the property, where a class inherits properties of more than one class. Java does not support multiple inheritance through classes. In java, multiple inheritance is implemented using interfaces. An interface contains methods and constants. These methods are abstract and do not have the method body. These methods are implemented through classes. To know more on interfaces, Read this: Using Interface in Java with an Example

In this post, we will see how we can implement multiple inheritance using interfaces with an example. The below Java program demonstrates the use of interface to implement multiple inheritance. Have a look at the given program to better your understanding of the concept.

interface StudentRead{
    void read();
}

interface StudentWrite{
    void write();
}

class Student implements StudentRead, StudentWrite{
    public void read(){
        System.out.println("The students read.");
    }
    public void write(){
        System.out.println("The students write.");
    }
}

public class Main
{
  public static void main(String[] args) {
    Student s = new Student();
    s.read();
    s.write();
  }
}

Output:

The students read.
The students write.

Now let’s try to understand the code. First, we have declared interfaces StudentRead and StudentWrite that have abstract methods read() and write() respectively. The class Student implements both of these interfaces and hence inheriting properties from these two.

Then in the main() method, we create an object of class Student and make a call to these methods which gives the above output.

Stay healthy and keep coding.

Thank you.

Also read: Enumeration Interface in Java

Leave a Reply