Are defaults in JDK 8 a form of multiple inheritance in Java?

前端 未结 8 1766
北荒
北荒 2020-11-30 00:17

A new feature coming in JDK 8 allows you to add to an existing interface while preserving binary compatibility.

The syntax is like

public interface S         


        
相关标签:
8条回答
  • 2020-11-30 01:04

    In short: it's a compile time error, must override the method by hand in the implementation.


    Purpose of default method

    The major purpose to introduce default method in Java 8, is to make interface extendable, without breaking existing implementations (there are so many 3rd party Java libraries).

    And multiple inheritance like in C++ is actually intended to be avoided, that's definitely not the purpose of default method in Java.


    How to override

    2 options:

    • Override the method, with its own logic.
    • Override the method, call one of the interface's method via super, format: <interface_name>.super.<method_name>();

    Tips:

    • method from interface is default to public, so don't forget to add public keyword when override it.
    0 讨论(0)
  • 2020-11-30 01:05

    My answer to your question is: Yes, it is a form of multiple inheritance, because you can inherit behavior from different parents. What's missing is to inherit states, i. e., attributes.

    Yes, but you can add getters and setters to your interface that the implementing classes then must implement. Nevertheless, the implementing classes don't inherit attributes. So, AFAICS, it's more like a trait-style solution rather than a multiple inheritance style solution.

    0 讨论(0)
提交回复
热议问题