使用lambda表达式,实现只有一个抽象方法的接口。
package rxxj;
public interface MyInter {
void print(String x);//只有一个抽象方法的接口
}
package rxxj;
public class Test{
public void test(MyInter i){
i.print("world");
}
//
public static void main(String []args){
Test at = new Test();
at.test(x->{
System.err.println("hello "+x);//使用lambda表达式实现接口
});
}
}
//匿名内部类实现函数式接口
package rxxj;
public class Test{
public static void main(String []args){
MyInter myInter = new MyInter() {
@Override
public void print(String x) {
System.err.println(x);
}
};//创建匿名内部类实现函数式接口
myInter.print("hello");
}
}
package rxxj;
public class Test{
public static void main(String []args){
MyInter myInter = System.out::println;
MyInter myInter2 = (x)->{
System.err.println(x);
};
MyInter myInter3 = (x)-> System.err.println(x);//使用lambda实现函数式接口
myInter.print("hello");
myInter2.print("hello");
myInter3.print("hello");
}
}
//引用接口中的静态方法,对接口实例化
package rxxj;
public interface MyInter {
void print(String x);//只有一个抽象方法的接口
static void demo(String x){
System.err.println("静态方法"+x);
}
}
package rxxj;
public class Test{
public static void main(String []args){
MyInter myInter1 = MyInter::demo; //引用接口中的静态方法,然后对接口实例化
myInter1.print("cc");
}
}