Java接口上的多重继承 [英] Multiple inheritance on Java interfaces

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

问题描述

我认为多重继承在Java中总是非法的,但是这段代码编译:

I thought multiple inheritance was always illegal in Java, but this code compiles:

public interface A {
  void a();
}

public interface B {
  void b();
}

public interface AB extends A, B {
}

是否会将 AB 等空接口视为不良做法?有没有办法在避免空接口(使用泛型或其他方式)的同时实现类似的东西?

Would having an empty interface such as AB be considered a bad practice? Is there a way to achieve something similar while avoiding the empty interface (using generics or otherwise)?

注意:我不是在问如何通过接口模拟多重继承。我意识到我可以执行以下操作:

Note: I'm not asking how to simulate multiple inheritance via interfaces. I realize I could do the following:

public class AbImpl implements A, B {
  public void a() {}
  public void b() {}
}

出于各种原因我需要一个具有两种方法的接口。

For various reasons I need an interface that has both methods.

推荐答案

不允许多次继承实现。但是,组件可以继承多个接口。

Multiple inheritance of implementations is not allowed. Components can inherit multiple interfaces, though.

继承多个接口不成问题,因为您只是定义要实现的新方法签名。它是多个功能副本的继承,传统上被视为导致问题,或者至少是混乱(例如,钻石死亡)。

Inheriting multiple interfaces isn't problematic, since you're simply defining new method signatures to be implemented. It's the inheritance of multiple copies of functionality that is traditionally viewed as causing problems, or at the very least, confusion (e.g., the diamond of death).

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

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