Search code examples
javalambdainterface

How can I define Lambda Expression for an interface with more than one method?


I can not define a lambda expression for an interface with multiple methods shown in the code below.

interface Interface{
    public void st1();
    public String ra(String p);
}

I can define a lambda expression for a single-method interface.

interface Interface{
    public String ra(String p);
}

public static void main(String[] args) {
    Interface r = (x)->{
        return x;
    };
    String getValue = r.ra("string");
    System.out.println(getValue);
}

But how can I define a lambda Expression for multiple methods?


Solution

  • You're thinking about functional interfaces. Anonymously defining a class with a lambda expression is a syntactic sugar that's only available for interfaces with a single method. If you have more than one method, you'll have to resort to a good old fashioned anonymous class:

    Interface r = new Interface() {
        public void st1() {
            // do something;
        }
    
        public String ra(String p) {
            return p;
        }
    }