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

前端 未结 8 1781
北荒
北荒 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:52

    "How will we distinguish the methods" was a question that was put on Stackoverflow and referred to this question concrete methods in interfaces Java1.8

    The following is an example that should answer that question:

    interface A{
    default public void m(){
    System.out.println("Interface A: m()");
    }
    }
    
    interface B{
    default public void m(){
    System.out.println("Interface B: m()");
    }
    }
    
     class C implements A,B { 
    
     public void m(){
      System.out.println("Concrete C: m()");   
     }
    
    public static void main(String[] args) {
       C aC = new C();
       aC.m();
       new A(){}.m();
       new B(){}.m();
    }
    }
    

    Class C above must implement its own concrete method of the interfaces A and B. Namely:

     public void m(){
      System.out.println("Interface C: m()");   
     }
    

    To call a concrete implementation of a method from a specific interface, you can instantiate the interface and explicitly call the concrete method of that interface

    For example, the following code calls the concrete implementation of the method m() from interface A:

    new A(){}.m();
    

    The output of the above would be:

    Interface A: m()

提交回复
热议问题