This is an example of how to use an anonymous inner class. We have created a class, TalkingClock
, that is a clock that prints the time in regular intervals and use it in another class, as described in the following steps:
TalkingClock
has a methodstart(int interval, final boolean beat)
. The method creates a new ActionListener object that overrides theactionPerformed(ActionEvent event)
of the ActionListener interface. This method will be invoked when the action will occur. In this method a new Date object is created and an audio beep is emitted, withbeep()
API method of Toolkit.- A new Timer is created in the
start(int interval, final boolean beat)
method to fire the ActionEvent at a given interval and itsstart()
method is used. - We create a new instance of
TalkingClock
and call itsstart(int interval, final boolean beat)
method. - We also bring up an information-message dialog titled with the message “Quit Program?”, using
showMessageDialog(Component parentComponent, Object message)
API method of JOptionPane. - The program will keep running until the user selects
OK
. Then theSystem.exit(0)
to end the application.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class AnonymousInnerClassTest {
public static void main(String[] args) {
TalkingClock timer = new TalkingClock();
timer.start(1000, true);
// keep program running until user selects "Ok"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
/**
* A clock that prints the time in regular intervals.
*/
class TalkingClock {
/**
* Starts the clock.
*
*/
public void start(int interval, final boolean beat) {
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
Date now = new Date();
System.out.println("The time is " + now);
if (beat){
Toolkit.getDefaultToolkit().beep();
}
}
};
Timer timer= new Timer(interval, listener);
timer.start();
}
}
This was an example of how to use an anonymous inner class in Java.