Interface default determination rule java

1 Introduction

jdk1.8 new addition to the default keyword, that is, increase the default interface can be achieved.

Because all changes without modifying the interface implementation class must change, so increase the default keyword after the other class, the default class for all implementations of the method increases.

2. Conflict

A class implements two interfaces, both interfaces have the default keyword default, the program will first perform which one do?

public interface A {
    default void hello() {
        System.out.println("Hello from A");
    }
}
public interface B extends A{
    default void hello() {
        System.out.println("Hello from B");
    }
}    
public class C implements B,A{
    
    public static void main(String[] args) {
        new C().hello();//Hello from B
    }
}

The answer is to perform B

Because there are three rules

Priority of the highest priority. Class or parent class declarations for methods in a class higher than 1. The method of any claims priority as the default method.

2. The sub-interface highest priority.

3. Under the case 12 can not determine, only the display cover.

 

Because where B inherits A, so the priority B is higher than A.

Guess you like

Origin www.cnblogs.com/lishuaiqi/p/12088943.html