//定义一个函数式接口
@FunctionalInterface
public interface Printable {
void print (String s);
}
public class DemoPrintable {
//定义一个方法,参数为函数式接口
public static void print(Printable printable){
printable.print("hello world");
}
public static void main(String[] args) {
//Lambda表达式
print((String s)->{
System.out.println(s);
});
//方法引用
//方法引用的前提,引用对象时存在的,对象的方法也是存在的
print(System.out::println);
}
}
通过类名引用静态成员方法
//定义一个函数式接口
@FunctionalInterface
public interface Printable {
void print (String s);
}
public class MethodDemo {
//自定义静态成员方法
public static void print(String s){
//将字符串转换成大写输出
System.out.println(s.toUpperCase());
}
public static void print1(Printable printable){
printable.print("hello world");
}
public static void main(String[] args) {
//通过类名引用静态成员方法
print1(MethodDemo::print);
}
}
引用父类的成员方法
@FunctionalInterface
public interface Greetable {
void gaeet();
}
//定义一个父类
public class Human {
public void sayHello(){
System.out.println("hello,我是Human");
}
}
public class Man extends Human {
@Override
public void sayHello() {
System.out.println("hello,我是man");
}
public static void greet1(Greetable greetable){
greetable.gaeet();
}
public static void main(String[] args) {
//创建父类对象
Human human=new Human();
//引用父类成员方法
greet1(human::sayHello);
}
}
构造方法引用
@FunctionalInterface
public interface Personable {
//传递一个方法,根据传递的姓名,创建Person对象
Person createPerson(String name);
}
public class Person {
String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class DemoPerson {
public static void get(String name,Personable personable)
{
Person person = personable.createPerson(name);
System.out.println(person.getName());
}
public static void main(String[] args) {
get("胡歌",Person::new);
}
}