'Using links to static and non-static methods with interface
Why I can call non-static method length() from class String, but I can't call non-static method lengthHelper( String line ) from my class ExpressionHelper?
public static void main(String[] args) {
String[] lines1 = {"H", "HH", "HHH"};
System.out.println(sum(lines1, String::length));
System.out.println(sum(lines1, s -> s.length()));
System.out.println(sum(lines1, ExpressionHelper::lengthHelper)); //wrong
}
interface Expression {
int length(String line);
}
static class ExpressionHelper {
int lengthHelper(String line) {
return line.length();
}
}
private static int sum(String[] lines, Expression func) {
int result = 0;
for (String i : lines) {
result += func.length(i);
}
return result;
}
Solution 1:[1]
String::length is an instance method of String. It requires an instance of String to run, which you are providing, because you are passing elements of lines1 to it.
ExpressionHelper::lengthHelper is an instance method of ExpressionHelper. In addition to the explicit String line argument, it requires an instance of ExpressionHelper to run, which you are not providing.
If you made lengthHelper a static method in ExpressionHelper, then you would be able to call it without an instance of ExpressionHelper.
Solution 2:[2]
In addition to the answer from khelwood:
If you change your code like this:
public static void main( String[] args )
{
final var expressionHelper = new ExpressionHelper();
String[] lines1 = {"H", "HH", "HHH"};
System.out.println(sum( lines1, String::length ) );
System.out.println(sum( lines1, s -> s.length() ) );
System.out.println(sum( lines1, ExpressionHelper::lengthHelper) ); //wrong
System.out.println(sum( lines1, expressionHelper::lengthHelper) );
}
it works also with ExpressionHelper::lengthHelper (although I should write better ExpressionHelper.lengthHelper() or ExpressionHelper#lengthHelper to avoid further confusion …)
Yes, I know, in this context it is nasty to name the variable same as the class, only having the first letter as lower case: it does not support readability.
But now expressionHelper is that instance of ExpressionHelper that @khelwood mentioned as missing in their answer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | khelwood |
| Solution 2 | tquadrat |
