I'm learning Lambda expressions and method references in Java 8 and see that we can refer to the super-class version of a method by use of 'super', as:
super::name
But when I do this, it is not working. Here is the sample code:
interface MyInterface {
int someFunc(int x);
}
class A {
static int Func(int y) {
// return (int) (Math.random() * y);
return y;
}
}
class B extends A {
static int Func(int y) {
// return (int) (Math.random() * y);
return y + 1;
}
}
public class Test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
java.util.Scanner scanner = new java.util.Scanner(System.in);
int result = funcOp(B::Func, scanner.nextInt()); // <-This works.
//int result = funcOp(B.super::Func, scanner.nextInt()); <--This is not working.
//Getting: error: not an enclosing class: B
int result = funcOp(B.super::Func, scanner.nextInt());
^
scanner.close();
System.out.println(result);
}
static int funcOp(MyInterface mI, int num) {
return mI.someFunc(num);
}
}
Please tell me, am I implementing this code wrong? From what I understood, we can pass a method "X" as reference in place where implementation for method "Y" of a functional interface is expected since method "X" satisfies the conditions and behavior of method "Y" and could potentially replace method "Y" in that situation.
Is this not right,did I get methods references in the wrong way?
Thanks for your inputs on this :)