4

I am trying to understand a program in java which has used lambda to return object into the reference variable of an interface. I want to convert lambda into simple java function, but not sure how to do it.

The program is as follows:

public abstract class Performance implements Serializable
{ 
    InterfaceName vehicle =(InterfaceName & Serializable) () ->{return new Object();};
    Object speed() 
    {
        return vehicle.speed();
    }
}

The interface is as follows:-

public interface InterfaceName 
{
    Object speed();
}

How could I convert this program into a simple Java program without use of a lambda, as a learning exercise?

2 Answers 2

4

You could replace lambda expression with your own implementation of the InterfaceName interface.

class InterfaceNameImpl implements InterfaceName {
    @Override
    public Object speed() {
        return new Object();
    }
}

Subsequently, you can replace your statement that uses lambda expression with

InterfaceName vehicle = new InterfaceNameImpl();

You can even use anonymous classes without explicitly having the above class that implements InterfaceName

InterfaceName vehicle1 = new InterfaceName() {
    @Override
    public Object speed() {
        return new Object();
    }
};

On a different note, you could even simplify your lambda usage from

InterfaceName vehicle =(InterfaceName & Serializable) () ->{return new Object();};

to

InterfaceName vehicle = () -> new Object();

or an even shorter version is

InterfaceName vehicle = Object::new;

In case, you want to understand how lambdas are implemented internally by the compiler you can go through Java-8-Lambdas-A-Peek-Under-the-Hood

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot Madhusudana. This is really helpful. I want to ask you that does typecasting to (InterfaceName & Serializable) makes any difference or not and what is (&) doing here.
@ela If you use with both vehicle =(InterfaceName & Serializable)..., it allows us to typecast vehicle to either of the above types.You can test the same with using instanceof operator on vehicle and it would return true for both. Anyways, if you don't use (InterfaceName & Serializable) it can't be typecasted to Serializable and only be typecasted to InterfaceName.
0

Delete the field entirely. This is the same:

public abstract class Performance implements InterfaceName {
    Object speed() {
        return new Object();
    }
}

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.