简体   繁体   English

如何组织类接口的层次结构?

[英]How to organize class interfaces hierarchy?

由于您可以使用类接口进行多重继承,因此您要遵循一些具体规则来创建和组织它们,例如,以避免接口重叠?

Java (at least up to Java 7) does not support multiple implementation inheritance, only multiple interface inheritance. Java(至少Java 7之前)不支持多重实现继承,仅支持多重接口继承。 I guess you are referring to a situation like this one: 我猜您指的是这样的情况:

public class Overlapping {

    interface A {
        void myMethod();
    }

    interface B {
        void myMethod();
    }

    static class C implements A, B {
        public void myMethod() {
            System.err.println("it works!");
        }
    }

    public static void main(String[] args) {
        new C().myMethod();
    }
}

This is not a problem (it works!). 这不是问题(有效!)。 If API overlaps, it just merges. 如果API重叠,则仅合并。

Here is a useful article about multiple inheritance in Java. 是有关Java多重继承的有用文章。

I think you are talking about stuff like this: 我认为您正在谈论的是这样的事情:

interface I1 {
   void methodName ();
}

interface I2 {
   void methodName (); //same method name
}

public Class MyClass implements I1, I2 {...}

I don't know any concrete rules to for such situation, because they are very rare. 我不知道针对这种情况的任何具体规则,因为它们很少见。 (Not like in C#, there is a construct (explicit interface implementation) for this "use"-case). (与C#不同,此“使用”用例有一个构造(显式接口实现))。

In my humble opinion this case is and should be very very rare. 以我的拙见,这种情况现在而且应该非常罕见。 Just try to avoid it ( /to hold it like this ). 只是尝试避免它( /像这样保持它 )。 So it is more a academical, not praxis relevant problem. 因此,这更多是学术上的,而不是实践上的相关问题。

The general rule that I follow is Separation of Concerns : every interface should model only one precise aspect or functionality, thus you can inherit multiple interfaces without having overlapping issues. 我遵循的一般规则是关注点分离 :每个接口都应该仅对一个精确的方面或功能建模,因此您可以继承多个接口而不会出现重叠的问题。 You may want to read also this question , and related answers. 您可能还需要阅读此问题和相关答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM