1

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?

Hulk
  • 6,399
  • 1
  • 30
  • 52
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • See the dupe as the key point here is "If the body of a lambda is a statement expression (that is, an expression that would be allowed to stand alone as a statement), it is compatible with a void-producing function type; **any result is simply discarded**." same applies in this case. – Ousmane D. Dec 07 '18 at 14:18

1 Answers1

4

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'
    }
}
Naman
  • 27,789
  • 26
  • 218
  • 353