How to organize class interfaces hierarchy?

2019-08-04 22:11发布

问题:

Since you can do multiple inheritance with class interfaces do you follow some concrete rules to create and organize them so as to avoid overlapping of interfaces for example ?

回答1:

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.



回答2:

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.



回答3:

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.