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?
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