Let us see Lambda expressions in Java which are already introduced in C#. Lambda expressions might be quite interesting and easy if you understand and concentrate a bit.
The use of lambda expressions is that we don’t need to know what is the method. You’ll have to note that it is not applicable for functions having different names but with same parameters instead it is only applicable only for functions that are overloaded.
These lambda expressions are used in the following program in implementing interface. See how easy implementing it was made.
ButtonAction.java
import javax.swing.*;
import java.awt.*;
class ButtonAction extends JFrame {
JButton b;
public ButtonAction() {
setTitle("Button Action");
setSize(400, 400);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
b = new JButton("Button");
b.addActionListener(
ae - > {
System.out.println("You clicked the button");
}
);
add(b);
}
public static void main(String args[]) {
new ButtonAction();
}
}
Output You clicked the button
Understanding the code
b.addActionListener(ae -> {
System.out.println("You clicked the button");
});
Notice that there is no new ActionListener()
and no public void actionPerformed(ActionEvent ae)
. Here the compiler understands that there is only one method in the ActionListener
interface and that takes only one parameter.
So obviously, it decides (finalizes) that the ae
is a reference to ActionEvent
. The code written in the actionPerformed(ActionEvent)
is enclosed as usual in the curly braces.
To be sure that ae
is the reference to ActionEvent
consider calling getSource()
method.
One more advantage is that we do not need to import the ActionListener
or ActionEvent
from java.awt.event
package. Note that these lambda expressions work only in Java 8 (may be in the future).
No comments:
Post a Comment