方法引用第四版

  • lambda表达式方法引用简化,有三种语法结构:
  1. 类名::静态方法名
  2. 实例对象::实例方法名
  3. 类名::实例方法名

1、类名A::静态方法名a

1.1、接口中的抽象方法无参数无返回值

  • 接口里的抽象方法在定义时没有用到A类,有没有用到不重要,只是在实现抽象方法时,调用了A类的静态方法a
package com.methodreference;

import org.junit.Test;

public class MethodRef {
    public void demo1(A a) {
        a.aMethod();
    }

    @Test
    public void test1() {
        demo1(new A() {
            @Override
            public void aMethod() {
                Student.xxx();
            }
        });//Student里的静态方法demo

        demo1(() -> Student.xxx());//Student里的静态方法demo

        demo1(Student::xxx);//Student里的静态方法demo

    }
}

interface A {
    void aMethod();
}

class Student {
    private String name;
    private int age;
    private String gender;
    private String city;
    private String score;

    public Student() {
    }

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

    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;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getScore() {
        return score;
    }

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

    public void eat() {
        System.out.println("Student的eat方法");
    }

    public static void xxx() {
        System.out.println("Student里的静态方法demo");
    }

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

你可能感兴趣的:(#,方法引用,java,intellij-idea,开发语言,Lambda,方法的引用,methodreference)