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).

11
  • Both questions have already been answered in the previous question that you asked. Quit posting duplicates. Commented Jul 7, 2015 at 12:03
  • Both questions are different. And the difference is easily noticable. Commented Jul 7, 2015 at 12:06
  • 3
    The accepted answer to your previous question already explains the reason for statement 1 resulting in a compilation error (See the comments section if you have a short term memory ;) ) Commented Jul 7, 2015 at 12:07
  • @ChetanKinger : You are right, but my question is why the second statement is not producing error Commented Jul 7, 2015 at 12:09
  • That has also been answered in your previous question. Commented Jul 7, 2015 at 12:10

1 Answer 1

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(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.