How do I replace an anonymous class with a lambda in Java?

Generally, something like this: methodUsingYourClass(new YourClass() { public void uniqueMethod(Type1 parameter1, Type2 parameter2) { // body of function } }); is replaced with methodUsingYourClass((parameter1, parameter2) -> { // body of function }); The types of the parameters can be inferred from usage, but there may be situations where specifying them is useful. This part from … Read more

What is the $1 in class file names?

Those are the .class files that hold the anonymous inner classes. In your example WelcomeApplet.java contains a top-level class (called WelcomeApplet) and an anonymous inner class, which will be stored in WelcomeApplet$1.class. Note that the exact name of the files holding anonymous inner classes is not standardized and might vary. But in practice I’ve yet … Read more

Java 8 Lambda Expressions – what about multiple methods in nested class

From JLS 9.8 A functional interface is an interface that has just one abstract method, and thus represents a single function contract. Lambdas require these functional interfaces so are restricted to their single method. Anonymous interfaces still need to be used for implementing multi-method interfaces. addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { … … Read more

How to pass parameters to anonymous class?

Yes, by adding an initializer method that returns ‘this’, and immediately calling that method: int myVariable = 1; myButton.addActionListener(new ActionListener() { private int anonVar; public void actionPerformed(ActionEvent e) { // How would one access myVariable here? // It’s now here: System.out.println(“Initialized with value: ” + anonVar); } private ActionListener init(int var){ anonVar = var; return … Read more