Being a fan of the Pomodoro technique I'm making myself a countdown timer to keep me on task with my homework. This particular project, however, is NOT homework. :)
Stack has a LOT of questions about using timers to control delays before user input and the like, but not a lot on standalone timers. I've run across this code from a friend, and have studied the class on Java Documentation.
public class Stopwatch {
static int interval;
static Timer timer;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Input seconds => : ");
String secs = sc.nextLine();
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = Integer.parseInt( secs );
System.out.println(secs);
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
System.out.println(setInterval());
}
}, delay, period);
}
private static final int setInterval()
{
if( interval== 1) timer.cancel();
return --interval;
}
}
There is some syntax that's not clear to me. Consider:
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
System.out.println(setInterval());
}
}, delay, period);
I'm not understanding how the parentheses and braces work. At first glance, given the usage of scheduleAtFixedRate(TimerTask task, long delay, long period)
I can see the delay
and period
parameters, but not an open paren preceding first parameter.
Is my first parameter actually this whole block of code? I would expect the whole block to be surrounded by parentheses...but it's not. Is this a common syntax in java? I've never run across it before.
new TimerTask() { public void run() { System.out.println(setInterval()); } }
I just want to clarify that I understand it before I start mucking about with changes.
It is a anonymous inner class. You need to study inner classes for understanding this. Generally such classes are used when you do not need the class to be used else where in your code. You cannot use it else where just because you dont have reference pointing to it. You can also replace the above code as follows :
That code is equivalent to this refactoring, where the
new TimerTask
is assigned to a local variable.Of course the weird part has just moved upwards a bit. What is this
new TimerTask
stuff, exactly?Java has special syntax for defining anonymous inner classes. Anonymous classes are a syntactical convenience. Instead of defining a sub-class of
TimerTask
elsewhere you can define it and itsrun()
method right at the point of usage.The code above is equivalent to the following, with the anonymous
TimerTask
sub-class turned into an explicit named sub-class.You are correct, the first parameter is the entire code block:
These declarations are called Anonymous classes and are explained in more detail in the Java Tutorials.