0

Now I am learning Java and I have written a code like this:

public class LambdaClass {
    public static void main(String args[]) {
        Plane pl = () -> {
            System.out.println("The plane is flying...");
        };

        pl.fly();
    }

    interface Plane {
       void fly();
       //void speedUp(); if I uncomment this, it is an error
    }
}

and I am interested in what is the connection between the lambda expression and the Plane interface methods, I mean is lambda expression's body statements now assigned to fly method of pl instance and why is it so?

1
  • 1
    Kindly go through some lambda tutorials. Google for some others. Try to understand what lambda actually is. Commented Mar 16, 2015 at 18:38

2 Answers 2

2

One requirement for using lambda implementations of an interface is for the interface to be functional, i.e. to have exactly one method.

When you define your interface with a single method fly(), Java considers it functional, and lets you implement it with a lambda. Once you add a second method, however, using lambdas becomes impossible, because the compiler needs to know which of the two methods you wish to implement.

One way to work around this issue would be defining separate functionali interfaces for each method, and then combining them into a bigger interface, like this:

interface Flyable {
    void fly();
}
interface WithSpeedIncrease {
    void speedUp();
}
interface WithSpeedDecrease {
    void slowDown();
}
interface Plane extends Flyable, WithSpeedIncrease, WithSpeedDecrease {
}
Sign up to request clarification or add additional context in comments.

Comments

0

Lambda expressions substitute for anonymous inner classes that implement functional interfaces.

A functional interface is an interface with exactly one non-default method, such as your Plane interface.

Your lambda expression is equivalent to an anonymous inner class that implements that interface's method with the lambda expression.

public static void main(String args[]) {
    Plane pl = new Plane() {
       @Override
       public void fly() {
           System.out.println("The plane is flying...");
       }
    };

    pl.fly();
}

The lambda expression is far more concise.

The reason that it doesn't compile if you uncomment the second method in the interface is that it will no longer be a functional interface. The lambda expression can only supply the implied method body for one method. If you have 2 methods in the interface, then the compiler won't have an implementation for a second method, much less not being able to choose between equivalent methods.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.