I want to create a built-in variable Runnable in lambda expressions, but for some reason the code is not compiled. Here is a sample code:

public class Module { public class Comand { Runnable command; String help; public Comand(Runnable command, String help) { this.command = command; this.help = help; } public static void main(String[] args) { Comand hello = new Comand(() -> System.out.println("Hello"), "helloworld"); } } } 

Here is the compilation error itself enter image description here

  • Where is your sample code? - JVic
  • I changed the example above from the top when I tried to do it - aleksandr kharitonov
  • And what error message does the compiler produce? - VladD
  • Well, who shows the code with a screenshot? Check without creating a runnable instance directly and check the JDK version - JVic
  • You do not create an instance of Module , so the compiler swears - Barmaley

2 answers 2

This is because inner classes cannot declare static declarations (fields, methods, blocks, etc.). In order for your code to work, you need to make the Comand class static.

 public class Module { public static class Comand { Runnable command; String help; public Comand(Runnable command, String help) { this.command = command; this.help = help; } public static void main(String[] args) { Comand hello = new Comand(() -> System.out.println("Hello"), "helloworld"); } } } 

Or you can even transfer the main method to the external class Module . So even better.

In general here in the documentation everything is described in detail about the nested classes.

  • Everything worked exactly! Thank you - aleksandr kharitonov
  • You're welcome. - Vanguard

You need to bring main into the outer class. And then create an instance of Module

 public class Module { public class Comand { Runnable command; String help; public Comand(Runnable command, String help) { this.command = command; this.help = help; } } public static void main(String[] args) { Module module = new Module(); Comand hello = module.new Comand(() -> System.out.println("Hello"), "helloworld"); } }