Abstract classes and Multiple Inheritance

前端 未结 5 1340
南笙
南笙 2021-01-19 15:02

We can achieve the same functionality as interfaces by using abstract classes, So why java doesn\'t allow the following code?

abstract class Animals
{
    pu         


        
5条回答
  •  野的像风
    2021-01-19 15:42

    This is because abstract classes are still classes, and inheritance is different than implementing an interface. Please see the differences between abstract class and interface. Also please see differences between inplementing an interface and extending a class in Java.

    This both questions covers all the information you need to know to understand why you can't have multiple inheritance of abstract classes.

    Also let me give you an example why this should not be allowed: Suppose you have the both Animals and Animals1 implementing the same interface IAnimals:

    interface IAnimals
    {
        public string eat();
    }
    
    abstract class Animals implements IAnimals
    {
        public abstract void run();
        public string eat(){ return "Animals eating"; } 
    }
    
    abstract class Animals1 implements IAnimals
    {
        public abstract void run1();
        public string eat(){ return "Animals1 eating"; } 
    }
    

    If you now define your Dog class as you did:

    class Dog extends Animals,Animals1
    {
      public void run() {System.out.println("Run method");}
      public void run1() {System.out.println("Run1 method");}
    }
    

    It will have the method eat() too, which is not abstract so it can use it directly. What would be the return of this method for a dog? Which string will be returned, the one with Animals, or the one with Animals1?

    This is called the diamond problem, and it is a reason why in some programming languages it is not allowed multiple inheritance.

提交回复
热议问题