简体   繁体   中英

How to organize class interfaces hierarchy?

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

Java (at least up to Java 7) does not support multiple implementation inheritance, only multiple interface inheritance. 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.

Here is a useful article about multiple inheritance in 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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