Anonymous inner class – Part 2

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:

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?");
 * 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() {
public void actionPerformed(ActionEvent event) {
    Date now = new Date();
    System.out.println("The time is " + now);
    if (beat){
  Timer timer= new Timer(interval, listener);

This was an example of how to use an anonymous inner class in Java.

Exit mobile version