天天看点

Java 构造器的引用

package Object_Oriented;

import java.util.Objects;

public class Student implements Comparable<Student>{
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object obj) {
        if(obj==this)
            return true;
        //处理多态的弊端:向下转型
        if(obj==null)
            return false;

        if (obj instanceof Student){
            Student stu=(Student) obj;
            return this.age==stu.age&&this.name.equals(stu);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public int compareTo(Student o) {
//        return 0;  默认元素都是相等的
        return this.getAge() - o.getAge(); //年龄升序
    }
}

           
package Object_Oriented;

@FunctionalInterface
public interface StudentBuilder {
    Student buildStudent(String name, int age);
}

           
package Object_Oriented;

//类的构造器引用
public class Test {

    public static void main(String[] args) {
        build("Bill",21,(String str,int i)->{
            return new Student(str,i);
        });
        build("Lily",21,Student::new);
    }
    public static void build(String name,int age,StudentBuilder studentBuilder){
        Student student = studentBuilder.buildStudent(name,age);
        System.out.println(student.getName()+" "+student.getAge());
    }
}