Explain why java does not allow multiple inheritance of classes but allows multiple inheritance of interfaces

  • 2021-07-26 07:44:56
  • OfStack

First, look at the following code:


interface a{
  void b();
}
interface a1 extends a{
  void b();
}
interface a2 extends a{
  void b();
}
interface a12 extends a1,a2{
  void b();
}
public class Main {
  public static void main(String args[]){
 
  }
}

Both a1 and a2 above inherit the interface a, and both get the definition of b method. Then a12 inherits a1 and a2 multiple times. Similarly, a12 obtains the definition of b method.

But assuming that all the interfaces in the above code are replaced by classes, if a12 does not override b method, then if a1 implements b method, and then a2 also implements b method, which class does a12 inherit b method come from? It seems that it is not good to abandon any method here.

Therefore, there will be contradictions in multiple inheritance of classes.

Interfaces are not implemented concretely, so this contradiction will not occur.

Some people may ask, since you can inherit more without implementation, can abstract classes inherit more?

The answer is no!

Why not, please continue to pay attention to my blog ~

Well, let's talk about it now. I think abstract classes are similar to ordinary classes in inheriting more.

Look at the following code:


abstract class a{
  abstract void b();
  void c(){
    System.out.println("c()");
  }
  abstract void d();
  abstract void e();
  abstract void f();
}
 
abstract class b extends a{
  abstract void b();
  abstract void d();
  abstract void e();
  void f(){
    System.out.println("f()");
  }
  /*abstract void f();*/
}
 
abstract class c extends a{
  abstract void b();
  abstract void d();
  abstract void e();
  abstract void f();
}
 
public class Main {
  public static void main(String args[]){
  }
}

Suppose we have a class d that inherits b and c without overriding the f method, then the question arises, whose f method is used for the f method in the class d? You might think that the class b has been implemented, and of course it is the f method already implemented in the class b.

If you think so, then the java compiler also thinks that the abstract method f in the class c is also a feature worth preserving, and then the contradiction comes...

But if you use an interface, it is very simple. All interfaces are not implemented ~ so it doesn't matter which interface you inherit and override this method ~


Related articles: