Anonymous inner classes are used to implement event monitoring without creating separate class files, simplifying the process. The syntax is: new 803d012befffc980e9771cd4c4a17694 { // Implement the methods declared in the interface }. For example, in the Button class, adding an ActionListener listener can be achieved through an anonymous inner class whose actionPerformed method prints a message when the button is clicked. It simplifies the code and improves readability, but only accesses local variables and has no constructors or fields.
How Java anonymous inner classes implement event monitoring
Anonymous inner classes are a special class in Java that have no name , and directly inherits from another class. A common use of anonymous inner classes is to implement event listening.
Syntax:
new <SuperClass> { // 实现接口中声明的方法 }
Practical case:
Suppose we have a Button
class, which There is a addActionListener
method that allows us to add a listener object. The listener object needs to implement the ActionListener
interface, which declares a method named actionPerformed
.
The following code shows how to use an anonymous inner class to implement ActionListener
:
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main { public static void main(String[] args) { // 创建一个按钮 Button button = new Button("Click me"); // 添加一个匿名内部类作为监听器 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 当按钮被点击时执行的操作 System.out.println("Button clicked!"); } }); } }
When the button is clicked, the actionPerformed
method in the anonymous inner class will be called, and print the message "Button clicked!".
Advantages:
Note:
The above is the detailed content of How to implement event monitoring in Java anonymous inner classes?. For more information, please follow other related articles on the PHP Chinese website!