I have the following code:
public class RefDemo {
static class Demo implements Runnable {
public Demo() {
System.out.println(this.toString() + "-----");
}
@Override
public void run() {
System.out.println("run");
}
}
public static void main(String[] args) {
Runnable runnable = Demo::new; // lambda ref constructor method
runnable.run(); // does not do anything
System.out.println(runnable);
Runnable demo = new Demo(); // using new to create a Demo instance
demo.run();
System.out.println(demo);
}
}
Which prints:
RefDemo$Demo@7291c18f----- // lambda run constructor method print
RefDemo$$Lambda$1/793589513@34a245ab // main method print
RefDemo$Demo@7cc355be-----
run
RefDemo$Demo@7cc355be
I don't know why the code does not print run
when calling runnable.run();
Why does that happen?
Yes, any lambda expression is an object in Java.
Java For Testers Lambda expression is an anonymous method (method without a name) that has used to provide the inline implementation of a method defined by the functional interface while a method reference is similar to a lambda expression that refers a method without executing it.
The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same.
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
This code
Runnable runnable = Demo::new;
Is equivalent to this code
Runnable runnable = new Runnable() {
@Override
public void run() {
new Demo();
}
};
So you are not referring to the run
method of Demo
but to the constructor.
You are simply using Runnable
in too many places and confusing yourself. The following code makes it a bit clearer what is happening:
public class RefDemo {
static class Demo {
public Demo() {
System.out.println(this.toString() + "-----");
}
public void something() {
System.out.println("something");
}
}
public static void main(String[] args) {
Runnable runnable = Demo::new;
runnable.run();
System.out.println(runnable);
Demo demo = new Demo();
demo.something();
System.out.println(demo);
}
}
Runnable runnable = Demo::new;
means that you now have a reference to the constructor of Demo
(which still works after dropping the conformance to the Runnable
interface). And you store that reference in a variable of type Runnable
which only works because their functional interfaces are compatible. Calling run
on that reference then simply calls the constructor, not the run
/ something
method of Demo
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With