接口的多重继承歧义 [英] Multiple Inheritance Ambiguity with Interface

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

问题描述

我们都知道有关多重继承的钻石问题 -

We all know about the diamond problem regarding multiple inheritance -

   A
  / \
 B   C
  \ / 
   D

此问题描述了类 D 的模糊情况。如果类 A 有一个方法,并且两者都是 B 和/或 C 覆盖方法然后哪个版本的方法 D 覆盖?

This problem describe an ambiguous situation for class D. If class A has a method and both/either of B and/or C override the method then which version of method does D override?

此问题是否也适用于Java中的接口?如果没有,Java接口如何解决这个问题?

Is this problem also applicable for interfaces in Java? If not, how do Java interfaces overcome this problem?

推荐答案

菱形问题仅适用于实现继承( extends 。它不适用于 API 继承(在Java 8之前的所有Java版本中实现)。

The diamond problem only applies to implementation inheritance (extends in all versions of Java prior to Java 8). It doesn't apply to API inheritance (implements in all versions of Java prior to Java 8).

由于具有匹配类型签名的接口方法是兼容的,因此如果您继承两次相同的方法签名,则不存在菱形问题:匹配方法签名只是简单地合并。 (如果类型签名不相同,那么你也没有钻石问题。)

Since interface methods with matching type signatures are compatible, there is no diamond problem if you inherit the same method signature twice: matching method signatures simply coalesce instead. (And if the type signatures aren't the same, then you don't have the diamond problem either.)

在Java 7及以下版本中,继承的唯一方法实现代码是通过 extends 关键字进行的,该关键字最多只能限制一个父级。因此,没有多重实现继承,并且钻石问题不存在。

In Java 7 and below, the only way to inherit implementation code was via the extends keyword, which restricts to at most one parent. Therefore there is no multiple implementation inheritance and the diamond problem does not exist.

Java 8增加了一个新的皱纹,因为它允许接口具有实现代码。当您使用具有匹配签名的方法实现多个接口时,它仍然可以简单地回退到先前的行为(没有实现继承)。

Java 8 adds a new wrinkle because it allows interfaces to have implementation code. It still escapes the diamond problem by simply falling back to the previous behavior (no implementation inheritance) when you're implementing multiple interfaces with methods that have matching signatures.

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

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