Java 8 Interface引入新特性- static method, default method

default method

定义default方法

public interface Interface1 {

    void method1(String str);

    default void log(String str){
        System.out.println("I1 logging::"+str);
    }
}

default方法使用

public class Interface1Impl implements Interface1 {

    @Override
    public void method1(String str) {
    }

    public static void main(String[] args) {
        Interface1Impl interface1Impl = new Interface1Impl();
        interface1Impl.log("abc");
    }
}

执行结果:
I1 logging::abc

方法名冲突场景

public interface Interface2 {

    void method2();

    default void log(String str){
        System.out.println("I2 logging::"+str);
    }

}
public class MyClass implements Interface1, Interface2 {
    @Override
    public void method2() {
    }
    @Override
    public void method1(String str) {
    }
    @Override
    public void log(String str) {
        System.out.println("MyClass logging::" + str);
        Interface1.super.log(str);
    }
    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        myClass.log("abc");
    }
}

执行结果:
MyClass logging::abc
I1 logging::abc

static method

定义static方法

public interface Interface3 {
    void method3();
    
    default void print(String str) {
        if (!isNull(str))
            System.out.println("Interface3 Print: " + str);
    }
    
    static boolean isNull(String str) {
        System.out.println("Interface Null Check: " + str);
        return str == null;
    }
}

static方法使用

public class Interface3Impl implements Interface3 {
    @Override
    public void method3() {
    }
    
    public boolean isNull(String str) {
        System.out.println("Interface3Impl Null Check: " + str);
        return str == null;
    }
    
    public static void main(String args[]) {
        Interface3Impl obj = new Interface3Impl();
        obj.print("");
        obj.isNull("abc");
        Interface3.isNull("123");
    }
}

执行结果:
Interface Null Check: 
Interface3 Print: 
Interface3Impl Null Check: abc
Interface Null Check: 123

参考

Java 8 Interface Changes - static method, default method

你可能感兴趣的:(JAVA8,java,开发语言)