Interfaces for Custom Time Measurement in Java


Write a Java program to demonstrate the use of an interface for custom time measurement

  • The Timer interface defines three methods: start(), stop(), and getTimeElapsed().
  • The Main class provides an anonymous inner class implementation of the Timer interface.
  • In the main method, the timer is started, and some simulated work (sleeping for 2 seconds) is performed.
  • After the work is done, the timer is stopped, and the elapsed time is printed.

Source Code

interface Timer
{
	void start();
	void stop();
	long getTimeElapsed();
}
 
public class Main
{
	public static void main(String[] args)
	{
		Timer timer = new Timer()
		{
			private long startTime;
			private long stopTime;
 
			@Override
			public void start()
			{
				startTime = System.currentTimeMillis();
			}
 
			@Override
			public void stop()
			{
				stopTime = System.currentTimeMillis();
			}
 
			@Override
			public long getTimeElapsed()
			{
				return stopTime - startTime;
			}
		};
 
		timer.start();
 
		// Simulate some work
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
 
		timer.stop();
		System.out.println("Time Elapsed : " + timer.getTimeElapsed() + " milliseconds");
	}
}

Output

Time Elapsed : 2000 milliseconds

Example Programs