自己可能之后会常使用到lambda表达式,但之前对lambda表达式也不是太敢使用,因此进一步去学习lambda表达式并记录在此。
在以往的学习中,我们可能就只了解接口中仅仅有抽象的方法,但是随着不断地学习发现接口中又有了新的可能,话不多说上实验代码:
1 以往自己认知的接口
//首先是定义
interface inf{
public void method1();
public void method2(int i,int j);
public int method3(int i, int j);
// ...... 此处可以添加更多的抽象方法申明
}
//使用匿名内部类进行使用,要对抽象方法及进行实现
public class test{
public static void main(String[] args) {
inf one= new inf(){
public method1(){
}
};
inf two= new inf(){
public method2(int i , int j){
System.out.println(i+j);
}
};
inf three= new inf(){
public method3(int i , int j){
System.out.println(i+j);
return i+i
}
};
} }
看完以上的内容,可能会有人和我一样觉得太麻烦了,这个时候lambda表达式就出来了,马上进行使用:
记住一句口诀:拷贝小括号,写死右箭头,落地大括号;(拷贝接口中方法参数部分的括号,右箭头就是一个减号一个">",大括号就是"{ }"在其中放置具体的执行内容就好了)。
2 函数式接口
//首先明确什么是函数式接口呢?
//函数式接口指的是在接口中有且仅有一个抽象方法的接口就是了,
@FunctionalInterface
interface inf{
public void method();//此处可以是其他类型的抽象方法,但是只有一个
}
public class test{
public void main(String[] args){
inf t1 =()->{};//可以不做具体的操作,实现过程已经完成
inf t2 =()->{//具体的操作写在这里
System.out.println("操作");
};
}
}
//****************************分割线*************************************//
//接口中有参数有返回值函数使用
interface inf {
public int method(int i ,int j);
}
public class test {
public static void main(String[] args) {
inf one=(int i ,int j)->{
System.out.println("一定记得写上返回值");
return i+j;
}
}}
对于函数式接口在此补充以下:
@FunctionalInterface -->在自己准备书写一个函数式接口时,在接口前加上“@FunctionalInterface”会时刻检查书写是否符合规范,即是不是只有一个抽象方法;使用了它,倘若在此接口中加入两个抽象方法就会报错;
3 接口中default实现方法
@FunctionalInterface
interface inf {
public void method1();//以无参无返回抽象方法示意哈
default int wa(int i , int j){
System.out.println("try it");
return i+j;
}
default int wa2(int i , int j){ //默认方法可以不进行重写,直接使用实例对象".方法名"就好了
System.out.println("try it again");
return i+j;
}
}
public class test implements inf{
public static void main(String[] args) {
test tt=new test();
tt.wa2
}
}
注意,
- 一个类中可以含有多个default方法(默认方法);
2.一个类同时实现了两个具有相同的default方法时,编译器会报错,所以在类中需要对该方法进行重写。具体实验可以参照->问题截图(因为排版不太合适,所以就放过去了)
4 接口中静态实现方法
//接口中除了以上的,还有可以实现的方法
interface inf {
public void method();
public static int wa(int i ,int j){
System.out.println("fds");
return i+j;
}}
//调用时使用接口名进行调用即可
总结:目前所说的接口中,可以有三类方法:基本的抽象方法、默认方法、静态方法。每一类方法均有不同的意义和用法,所以还是。。多学!
学习中,如有错误欢迎指正!十分感谢