接口中默认方法修饰为普通方法
在jdk8之前,interface之中可以定义变量和方法
1.变量必须是public、static、final,
2.方法必须是public、abstract。
接口定义方法:public 抽象方法 需要子类实现
在JDK 1.8开始 支持使用static和default 修饰 可以写方法体,不需要子类重写。
方法:
普通方法 可以有方法体
抽象方法 没有方法体需要子类实现 重写。
public interface JDK8Interface {
void addOrder();
/**
* 默认方法 可以写方法体
*/
default void getDefaultOrder() {
System.out.println("我是默认方法 我可以写方法体");
}
static void getStaticOrder() {
System.out.println("我是静态的方法 可以写方法体");
}
}
public class JDK8InterfaceImpl implements JDK8Interface {
/**
* 默认和静态方法不是我们的抽象方法 ,所以不需要重写
*/
@Override
public void addOrder() {
System.out.println("addOrder");
}
}
Lambda表达式
Lambda 好处:
1.简化我们匿名内部类的调用。
2.Lambda+方法引入 代码变得更加精简。
Lambda 缺点:
1.可读性比传统写法要低,不好调试。
Lambda表达式的规范
使用Lambda表达式 依赖于函数接口
- 在接口中只能够允许有一个抽象方法
- 在函数接口中定义object类中方法
- 使用默认或者静态方法
- @FunctionalInterface 表示该接口为函数接口
Java中使用Lambda表达式的规范,必须是为函数接口
函数接口的定义:在该接口中只能存在一个抽象方法,该接口称作为函数接口
Java系统内置那些函数接口
消费型接口:
Consumer<T>
void accept(T t);
BiConsumer<T,U>
void accept(T t,U u);//增加一种入参类型
供给型接口
Supplier<T>
void get();
函数型接口
Function<T ,R>
R apply(T t);
UnaryOperator<T>
T apply(T t);//入参与返回值类型一致
BiFunction <T ,U,R>
R apply(T t,U u);//增加一个参数类型
BinaryOperator<T>
T apply(T t1,T t2);//l两个相同类型入参与同类型返回值
ToIntFunction<T>//限定返回int
ToLongFunction<T>//限定返回long
ToDoubleFunction<T>//限定返回double
IntFunction<R>//限定入参int,返回泛型R
LongFunction<R>//限定入参long,返回泛型R
DoubleFunction<R>//限定入参double,返回泛型R
断言型接口
Predicate<T>
boolean test(T t);
Lambda基础语法
()---参数列表
-> 分隔
{} 方法体
(a,b)->{
}
(函数接口的参数列表 不需要写类型 需要定义参数名称)->{方法体}
Lambda方法引入
类型 |
语法 |
对应lambda表达式 |
构造器引用 |
Class::new |
(args) -> new 类名(args) |
静态方法引用 |
Class::static_method |
(args) -> 类名.static_method(args) |
对象方法引用 |
Class::method |
(inst,args) -> 类名.method(args) |
实例方法引用 |
instance::method |
(args) -> instance.method(args) |
静态方法引入:
MessageInterface messageInterface2 = () -> {
MethodReference.getStaticMethod();
};
messageInterface2.get();
// 使用方法引入调用方法 必须满足:方法引入的方法必须和函数接口中的方法参数列表/返回 值一定保持一致。
MessageInterface messageInterface = MethodReference::getStaticMethod;
messageInterface.get();
对象方法引入:
Function<String, Integer> function2 = String::length;
System.out.println(function2.apply("test"));
实例方法引入:
Test009 test009 = new Test009();
MessageInterface messageInterface = test009::get;
messageInterface.get(1);
构造函数引入:
UserInterface UserInterface2= UserEntity::new;
UserInterface2.getUser();