0
import java.util.List;
import java.util.function.*;

interface SomeTest <T>
{
    boolean test(T n, T m);
}

class MyClass <T>
{
    boolean myGenMeth(T x, T y)
    {
        boolean result = false;
        // ...
        return result;
    }
}

class Timepass
{
    public static void main(String args[])
    {
        SomeTest <Integer> mRef = MyClass <Integer> :: myGenMeth;   //Statement 1

        Predicate <List<String>> p = List<String> :: isEmpty;       //Statement 2
    }
}

My query

In the above code, Statement 1 produces two compile time errors

1- Can not find method myGenMeth(Integer, Integer)

2- Non static method myGenMeth(T, T) can not be referenced from static context

Where as, Statement 2 shows no error.

1- What is the difference between Statement 1 and Statement 2??

2- How the Statement 2 is working fine.

(I am not asking why the Statement 1 is producing error).

kevin gomes
  • 1,775
  • 5
  • 22
  • 30

1 Answers1

1

Because you have method references to instance methods, but don't specify any specific instance, the instance needs to be passed as a parameter to the interface method.

For statement 2, you can pass this instance to the test method of Predicate:

p.test(new ArrayList<>());

But for statement 1, test doesn't take an instance as a parameter:

mRef.test(new MyClass<>(), 1, 2);

To make this compile, SomeTest needs to be changed to:

interface SomeTest<T> {
    boolean test(MyClass<T> instance, T n, T m);
}

Alternatively, you can make the method references refer to specific instances, then the interface method doesn't need to contain that parameter:

SomeTest <Integer> mRef = new MyClass<Integer>()::myGenMeth;
mRef.test(1, 2);

Supplier<Boolean> p = new ArrayList<>()::isEmpty;
p.get();
fgb
  • 18,439
  • 2
  • 38
  • 52