Java 接口如何模拟多重继承? [英] How do Java Interfaces simulate multiple inheritance?

查看:37
本文介绍了Java 接口如何模拟多重继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Java 教程"(第二次).我刚刚(再次)浏览了接口部分,但仍然不明白 Java 接口如何模拟多重继承.有没有比书上更清楚的解释?

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

卡车有一个 driveTo() 方法,而厨房有一个 Cook() 方法.

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

现在假设泡利决定从一辆送货卡车的后面卖比萨饼.他想要一个他可以用 driveTo() 和 cook() 的东西.

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.

在 C++ 中,他会使用多重继承来做到这一点.

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

在 Java 中,这被认为过于危险,因此您可以从主类继承,但您可以从接口继承"行为,这些行为出于所有意图和目的都是没有字段或方法实现的抽象类.

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.

所以在 Java 中我们倾向于使用委托来实现多重继承:

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

Pauli 将卡车子类化,并在名为 kitchen 的成员变量中为卡车添加厨房.他通过调用 kitchen.cook() 来实现 Kitchen 接口.

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)

这篇关于Java 接口如何模拟多重继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆