匿名内部类 创建对象和实现类的定义同步完成,必须实现一个接口或者继承一个类

package how2j;

//根据要求找到相关信息的学生对象
//java中不允许函数回调,所以将函数方放在类或者接口中,所以在使用时传的是对象,或者接口实现类产生的对象
//lambda表达式是匿名内部类的简单写法
public class LambdaFenXi {
    public static void main(String[] args) {
        Student[] ss = {// 学生对象存在数组里面
        new Student("alex", 18, 100.0), new Student("jay", 60, 30.0),
                new Student("moses", 40, 60.0) };
        // lambda表达式实现接口并且创建对象,调用find方法将对象传进去
        System.out.println(find(ss, stu -> stu.getScore() == 100.0));

    }

    public static Student find(Student[] ss, Test t) {// 寻找方法寻找符合条件的对象
        for (int i = 0; i < ss.length; i++) {
            if (t.test(ss[i])) {// 调用接口实现类new的对象的方法结果传过来
                return ss[i];
            }
        }
        return null;
    }
}

interface Test {// 将需要进行对比的条件写成接口放在方法里面
    boolean test(Student stu);
}

class Student {// 学生类
    private String name;
    private Integer age;
    private Double score;

    public Student() {
        super();
    }

    public Student(String name, Integer age, Double score) {
        super();
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public Double getScore() {
        return score;
    }

    public void setScore(Double score) {
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setscore(Double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", score=" + score
                + "]";
    }

}

 

posted on 2020-07-19 12:33  AlexLiuF  阅读(467)  评论(0编辑  收藏  举报