Thursday, 18 June 2020

Implementing Multiple Inheritance using Interfaces in Java

In java multiple inheritance is a OOPs concept where a single class / interfaces acquire the features of two parent classes. As we know inheritance feature in java can be implemented using either class or interfaces. Java do not support multiple inheritance using java because it creates a diamond problem or name conflicts and ambiguity. inheritance in java, multilevel inheritance in java,interface in java, java multiple inheritance workaround, hierarchical inheritance in java,hybrid inheritance in java,
types of inheritance in java

Why Java Does not support Multiple Inheritance using classes?

For example consider the following case where a class C inherited the features of class A and class B. Suppose the two parent classes contain same method names and same variable names, then while calling suing derived class object, the compiler is unable to decide which version of the super class method need to call. This ambiguity can be eliminated by using interfaces.

How to achieve multiple inheritance in java

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.

One of the main reason for introduction of interfaces in java is to implement multiple inheritance feature. Here we use two base classes as interface and derived / child class as class. For example consider the following figure 




 There are two ways by which we can implement multiple inheritance in java:

1. The two parent classes are interfaces and one child class
2. All parent and child classes as interfaces.

For example consider the following java program
interface Father
{
float HT=6.2F;
void height();
}
interface Mother
{
float HT=5.8F;
void height();
}
class child implements Father, Mother
{
  void height()
{
  float cht=(Father.HT+Mother.HT)/2;
  System.out.println(“child height=”+cht);
}
}
class AccessDemo
{
public static void mian(String args[])
{

    child ch=new child();
       ch.height();
}
}

Here the two interfaces have the same variable names "HT" and same methods "height()". These two are implemented in sub class child and there is no name conflicts and no ambiguity with this type of implementation. That is the reason why interfaces are used to implement multiple inheritance in Java.

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top