import java.util.function.Supplier;
public class Student {
public String name;
public static Student creatStudent(Supplier<Student> s) {
System.out.println("通过方法引用创建对象");
return s.get();
}
public static void eat(Student student) {
System.out.println("Student " + student.getName() + "is eating");
}
public void drink(Student s) {
System.out.println("student" + s.getName() + "drink something");
}
public void study() {
System.out.println("the student" + this.getName() + " has studyed 5 hours");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
System.out.println("this student's name is " + name);
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
@Override
public String toString() {
System.out.println("Student [name=" + name + "]");
return "Student [name=" + name + "]";
}
}
//测试类
import java.util.Arrays;
import java.util.List;
public class Test06 {
public static void main(String[] args) {
// 构造方法引用
Student s1 = Student.creatStudent(Student::new);
Student s2 = Student.creatStudent(Student::new);
s1.setName("张三");
s2.setName("李四");
Student[] ss = { s1, s2 };
// 静态方法引用
List<Student> listStu = Arrays.asList(ss);
listStu.forEach(Student::eat);
// 特定对象的方法引用
listStu.forEach(s1::drink);
// 特定类任意对象的特定方法
listStu.forEach(Student::toString);
listStu.forEach(Student::study);
}
}
out:
通过方法引用创建对象
通过方法引用创建对象
this student's name is 张三
this student's name is 李四
Student 张三is eating
Student 李四is eating
student张三drink something
student李四drink something
Student [name=张三]
Student [name=李四]
the student张三 has studyed 5 hours
the student李四 has studyed 5 hours
————————————————
版权声明:本文为CSDN博主「IQ等于猪」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sinat_41132860/article/details/84638568