Skip to content
Advertisement

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;
}

Advertisement

Answer

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.

Advertisement