I encountered code like this(I simplidied it a bit) in the article:
public class Main {
static class A {
}
public static void main(String[] args) {
new Thread(A::new).start();
}
}
I surprised about that code because from my point if view it must produce compile time error because Thread
constructor accepts Runnable
but A
doesn't have methid run
but it compiles and even starts without any errors/exceptions. I checked it on my PC in several variations and it works anyway.
So I have following questions:
Why there no compilation errors?
Which method executes instead of run method?
A Runnable
is a FunctionalInterface
which can also be represented in lambda expression as in your case:
new Thread(() -> new A())
which is nothing but a similar representation of method-reference
A::new
that in your code is equivalent to
new Runnable() {
@Override
public void run() {
new A(); // just creating an instance of 'A' for every call to 'run'
}
}