Java 9 Interface vs Class

前端 未结 5 1013
春和景丽
春和景丽 2020-12-08 02:11

As Java 9 is going to allow us to define private and private static methods too in interfaces, what would be the remaining difference in inte

5条回答
  •  情话喂你
    2020-12-08 02:52

    Private interface methods in Java 9 behave exactly like other private methods: They must have a body (even in abstract classes) and can neither be called nor overridden by subclasses. As such they do not really interact with inheritance. Talking of which (and particularly multiple inheritance), there are (at least?) three kinds of it:

    • Inheritance of types means that one type can be another type, e.g. String is an Object. Java allowed multiple inheritance of types from day one (via interfaces).
    • Inheritance of behavior means that one type can inherit the behavior of another type. Before Java 8, only classes could implement methods, so there was only single inheritance of this kind. With Java 8 came default methods, which allowed interfaces to implement methods, thus giving Java multiple inheritance of behavior.
    • Inheritance of state means that a type inherits another type's internal state (i.e. fields). As it stands (Java 9 and everything currently proposed for future Java versions), only classes can have state, so there is only single inheritance of this kind.

    As you can see private interface methods do not add anything here.

    Regarding your question of how interfaces and classes compare, there are two main differences: multiple inheritance and state. Interfaces support the former, classes can have the latter. Since state is kind-of important in typical OOP, classes will remain relevant.

提交回复
热议问题