java8-新特性-01-接口的默认方法和静态方法

1.接口里也可以写方法体了,实现该接口的类不再强制实现该方法,只需要在方法签名增加default签名并实现方法体.

2.接口可以定义静态方法,通过接口调用。实现类不需实现,也无法在实现类中直接调用(需要使用接口名称直接调用)


public interface Java8Interface {

    /**
     * 默认方法
     */
    default int add(int a,int b) {
        return a+b;
    }

    /**
     * 静态方法
     */
    static int sub(int a,int b) {
        return a - b;
    }

    String call(String message);
}

调用方式如下所示,是不是比之前方便很多了!(暂不考虑继承导致的歧义)

public class Java8InterfaceImpl implements Java8Interface {

    @Override
    public String call(String message) {
        return "hell : "+message;
    }

    public static void main(String[] args) {
        Java8InterfaceImpl model = new Java8InterfaceImpl();
        System.out.println(model.call("java8"));        // 调用实现的接口方法
        System.out.println(model.add(1,2));             // 调用接口默认的实现方法
        System.out.println(Java8Interface.sub(10,8));   // 调用接口静态的实现方法
    }
}

猜你喜欢

转载自blog.csdn.net/ming1215919/article/details/82782288