
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Lambda Expression Without Anonymous Class in Java
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
Advertisements