How do Java Interfaces simulate multiple inheritance?

I am reading "The Java Tutorial" (for the 2nd time). I just got through the section on Interfaces (again), but still do not understand how Java Interfaces simulate multiple inheritance. Is there a clearer explanation than what is in the book?


Suppose you have 2 kinds of things in your domain : Trucks and Kitchens

Trucks have a driveTo() method and Kitchens a cook() method.

Now suppose Pauli decides to sell pizzas from the back of a delivery truck. He wants a thing where he can driveTo() and cook() with.

In C++ he would use multiple inheritance to do this.

In Java that was considered to be too dangerous so you can inherit from a main class, but you can "inherit" behaviors from interfaces, which are for all intents and purposes abstract classes with no fields or method implementations.

So in Java we tend to implement multiple inheritance using delegations :

Pauli subclasses a truck and adds a kitchen to the truck in a member variable called kitchen. He implements the Kitchen interface by calling kitchen.cook().

class PizzaTruck extends Truck implements Kitchen {
   Kitchen kitchen;

   public void cook(Food foodItem) {
      kitchen.cook(foodItem);
   }
}

He is a happy man because he can now do things like ;

pizzaTruck.driveTo(beach);
pizzaTruck.cook(pizzaWithExtraAnchovies);

Ok, this silly story was to make the point that it is no simulation of multiple inheritance, it is real multiple inheritance with the proviso that you can only inherit the contract, only inherit from empty abstract base classes which are called interfaces.

(update: with the coming of default methods interfaces now can also provide some behavior to be inherited)


You're probably confused because you view multiple inheritance locally, in terms of one class inheriting implementation details from multiple parents. This is not possible in Java (and often leads to abuse in languages where it's possible).

Interfaces allow multiple inheritance of types, eg a class Waterfowl extends Bird implements Swimmer can be used by other classes as if it were a Bird and as if it were a Swimmer . This is the the deeper meaning of multiple inheritance: allowing one object to act like it belongs to several unrelated different classes at once.


Here is a way to achieve multiple inheritance through interfaces in java.

What to achieve?
class A extends B, C // this is not possible in java directly but can be achieved indirectly.

class B{
   public void getValueB(){}
}

class C{
   public void getValueC(){}
}


interface cInterface{
   public getValueC();
}

class cChild extends C implemets cInterface{
    public getValueC(){

      // implementation goes here, call the super class's getValueC();

    }
}


// Below code is **like** class A extends B, C 
class A extends B implements cInterface{
   cInterface child =  new cChild();
   child.getValueC();
}
链接地址: http://www.djcxy.com/p/53940.html

上一篇: 继承与聚合

下一篇: Java接口如何模拟多重继承?