Method reference in Java 8

前端 未结 5 1025
梦如初夏
梦如初夏 2021-02-13 15:31
public class Car {

    private int maxSpeed;

    public Car(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public int getMaxSpeed() {
        return maxS         


        
5条回答
  •  故里飘歌
    2021-02-13 16:15

    A member function with no parameters actually has a hidden parameter, the this reference. Method references of the form ClassName::memberFunction always use the first parameter of the functional type for the class instance, i.e. the instance's hidden this parameter. So, in the case of Car.getMaxSpeed(), internally it has the same parameters as a static Integer getMaxSpeed(Car car). Car::getMaxSpeed would therefore fit the functional type Function, just as a static Integer getMaxSpeed(Car car) would.

    Something similar happens with member functions that take one parameter--they fit the BiFunction functional type, with the first parameter being the class instance.

提交回复
热议问题