Java interface method call for Runnable [duplicate]

问题: This question already has an answer here: What is the breakdown for Java's lambda syntax? 4 answers How will Java lambda functions be compiled? 1 answ...


This question already has an answer here:

I am studying Java at my computer science class and I've found in the examples this line of code:

String name = "test";
Runnable r = () -> System.out.println(name);;

I know what a Runnable does and I also know that it is an interface. By my knowledge I know that it's not possible to create an instance of an interface. But looking at the above code it seems that it's possible to call interface methods.

Are anonymous classes involved here? I have studied that

new Thread(new Runnable()...)

Is not an instance of an interface but it's actually an anonymous class that implements an interface. Does the same happen with the code above? Are anonymous classes involved?


Runnable r = () -> System.out.println(name);

This line creates an instance of Runnable (since it is @FunctionalInterface, java-8 related). That code basically says that you now have an instance that overrides run method and produces that System.out.println(name).

That instance (and the class that represents that instance) is created at runtime btw, the exact way in which it is implemented is implementation specific. Right now, it is a class that implements your Runnable interface.

  • 发表于 2019-01-19 04:15
  • 阅读 ( 234 )
  • 分类:网络文章


请先 登录 后评论


作家榜 »

  1. 小编 文章