java8语法--Inteface接口篇

一、引言

     本部分文档从接口创建、接口定义、接口使用来理解java8对新增特性的处理。

二、Jdk接口默认方法与静态方法

代码测试

package com.hecore.grammar.java8;

public interface J8MulIface {

    //1. 同名默认方法
    default void run(){
        System.out.println("与另一个接口的默认方法同名,导致重名问题");
    }

    // 非同名默认方法
    default void mulRun(){
        System.out.println("防止与另一个接口的默认方法同名,不会有重名问题");
    }

    //2. 静态方法
    static void staicMethod(){
        System.out.println("static method");
    }

}

1.J8接口中有同名的默认实现问题:

com.hecore.grammar.java8.J84IMulfacelImpl inherits unrelated defaults for run() from types com.hecore.grammar.java8.J8Iface and com.hecore.grammar.java8.J8MulIface

思考:

继承类当引用第三方包实现的两接口都同名了怎么办?

(1).指定接口

public void run(){
    J8Iface.super.run();
}

(2).多接口调用

三、函数式接口

 @FunctionInterface用于检测是否为函数式接口以及语法是否合理。

不支持多于一个的抽象方法

 支持 默认方法、静态方法、Java.lang,Object中的方法。

四、接口方法引用

关键字 : :

/**
 * 方法引用就是lambda的一种简化写法,相当于把方法当成一个变量赋值给另一个方法,这个方法接受的参数是一个函数接口
 * 1.方法是static的: 类名::方法名
 * 2.方法不是static的:对象::方法名
 * 3.构造方法: 类名::new
 *
 * java8应用-->Collectors,查看源码会发现 内部实现机制便是实现lambda接口
 */
public class FunctionInvoke {

    // 接收函数式接口
    public static void ReceiveFunctionIface(FunctionIface fi){
        fi.deal("receive iface");
    }

    public static void main(String[] args) {

    }

}

/**
 * 1.定义函数式接口
 * 注解作用检测是否为函数式接口
 * 支持接口默认方法、静态方法、java.lang.Object方法
 */
@FunctionalInterface
interface  FunctionIface{
    void deal(String str);
}

/**
 * 不支持多个抽象方法
 */
//@FunctionalInterface
//interface  FunctionTestIface{
//    void deal();
//    void run();
//    void say();
//}


/**
 * 1.1实现函数式接口
 */
class FunctionIfaceImpl implements  FunctionIface{
    public void deal(String str){
        System.out.println(str+" is being deal");
    }
}
发布了49 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_24935049/article/details/88965265