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

前端 未结 8 1776
北荒
北荒 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 00:44

    There are two scenarios:

    1) First, that was mentioned, where there is no most specific interface

    public interface A {
       default void doStuff(){ /* implementation */ }
    }
    
    public interface B {
       default void doStuff() { /* implementation */ } 
    }
    
    public class C implements A, B {
    // option 1: own implementation
    // OR
    // option 2: use new syntax to call specific interface or face compilation error
      void doStuff(){
          B.super.doStuff();
      }
    }
    

    2) Second, when there IS a more specific interface:

       public interface A {
           default void doStuff() { /* implementation */ } 
        }
    
        public interface B extends A {
           default void doStuff() { /* implementation */ } 
        }
    
        public class C implements A, B {
        // will use method from B, as it is "closer" to C
        }
    

提交回复
热议问题