包含接口作为参数的方法

时间:2018-11-14 19:36:53

标签: java interface

你好我该如何调用一个以接口为主要参数的方法? 主要代码是我要实现的示例,但现在要调用方法map

我该如何在map方法中编写内容,以及如何在主方法中调用它?谢谢

我想要实现的目标:

StringTransformation addBlah = (e) -> {
    e += "boo";
     return e;
};
System.out.println(addBlah.transf("Hello")); // prints Helloboo

public class Main{

    public static void main(String[] args) {
        String a = hello;
        // How do I modify the string a by calling map ?


    }

    void map(StringTransformation t) {
        // What do I write ??
    }
}

public interface StringTransformation {
    String transf(String s);
}

2 个答案:

答案 0 :(得分:0)

您无法在F map方法内调用static。如果要这样做,还必须使main为静态方法。另外,如果您不告诉我们该怎么做,我们将无法为您提供map函数的内容。

map

答案 1 :(得分:0)

您想使用给定的String来修改StringTransformation,因此需要将它们都传递给map方法。您也可以使用更简单的lambda来打开addBlah

public static void main(String[] args) {
    StringTransformation addBlah = (e) -> e + "boo";

    String str = "Hello";
    System.out.println(str);    // Hello
    str = map(addBlah, str);
    System.out.println(str);    // Helloboo
}

static String map(StringTransformation t, String argument) { 
    return t.transf(argument);     
}