1

I am trying to understand the concept of Method references. When trying out different calls, I stumbled upon a scenario which I cant fully understand.

When canClim is used without a parameter, it can be passed to forEach without problems although forEach takes a Consumer which should take in a parameter? When adding a parameter to canClim it prevents compiling?

However when canClim is declared as static it won't compile without adding static void canClim(Animal a) to the signature. Shouldn't it be possible to call the static method without having a instance of the Animal class because it is static ?

Thanks!

import java.util.*;

class Animal {
    void canClim() {
        System.out.println("I am a climber!");
    }
}

public class MethodReferencer {
    public static void main(String[] args) {
        Animal a = new Animal();
        Animal b = new Animal();
        List<Animal> list = new ArrayList<>(Arrays.asList(a, b));
        list.forEach(Animal::canClim);

    }
}
5
  • docs.oracle.com/javase/tutorial/java/javaOO/… Commented Apr 24, 2019 at 5:47
  • You really need to read on how method references are resolved. It would be too broad to answer here. Commented Apr 24, 2019 at 5:53
  • 2
    You can think of an instance method Animal.canClim() as a function which takes an Animal (this) as argument: canClim(Animal this). When you think of it that way, it becomes obvious that this is a valid Consumer<Animal>. Static methods, on the other hand, have no this. Commented Apr 24, 2019 at 5:57
  • @JBNizet that makes sense, so the this is supplied to the accept of the consumer? Commented Apr 24, 2019 at 6:02
  • You got it right... Commented Apr 24, 2019 at 6:03

2 Answers 2

1

When the method is non-static,

Animal::canClim
is equivalent to
animal -> animal.canClim()
or (animal) -> animal.canClim()

The animal on the left side of the lambda is the consumer function parameter, and the body is on the right. So yes, you are supplying a consumer there.

Static methods behaves a bit differently.
For example, Integer::parseInt would become str -> Integer.parseInt(str).
Basically the parameter is supplied to the parameter of the method. So in static methods, you need to have a parameter to be able to use method references.

Sign up to request clarification or add additional context in comments.

Comments

0

The Consumer has a method accept that takes an argument. A static method with no argument couldn't be converted to a Consumer, could it?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.