How to implement lambda expression without creating an anonymous class in Java?

Java 8Object Oriented ProgrammingProgramming

A lambda expression is an anonymous function without having any name and does not belong to any class that means it is a block of code that can be passed around to execute.

Syntax

(parameter-list) -> {body}

We can implement a lambda expression without creating an anonymous inner class in the below program. For the button's ActionListener interface, we need to override one abstract method addActionListener() and implement the block of code using the lambda expression.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LambdaExpressionButtonTest extends JFrame {
   private JButton btn;
   public LambdaExpressionButtonTest() {
      btn = new JButton("Click on the button");
      // implement ActionListener for JButton using lambda expression
      btn.addActionListener(ae -> JOptionPane.showMessageDialog(null, "Button clicked !!!!"));
      add(btn, BorderLayout.NORTH);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(400, 300);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new LambdaExpressionButtonTest();
   }
}

Output

raja
Published on 09-Dec-2019 17:20:53
Advertisements