Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Timer Object

+4 votes
I was reading page 82 of our book and noticed a timer object being initialized.

final Timer timer = new Timer();

timer.schedule(new TimerTask() { public void run() {door.close(); timer.cancel();}}, 5000);

What is this format method(new TimerTask{public void run() {methods();}, int}? You can pass methods into a constructor?
asked Aug 29 in CSC 285 (F17) by Daniel Zwiener (3,754 points)

2 Answers

+3 votes
Best answer

Actually, what's going on is that you are creating a new anonymous inner class which extends the abstract TimerTask class, and defining (overriding) the run() method of that class.

So, you aren't technically passing a method into the constructor... you're passing a new instance of a new class (that is anonymous -- has no name) that you're defining on the spot.  (This class doesn't need to have a name, since it never gets used again... it existed just for the purpose of creating this object with this one overriden run() method.)

To learn more about how this works, see: https://www.javatpoint.com/anonymous-inner-class and  https://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java

Hope that helps!


answered Aug 30 by Forrest Stonedahl (3,438 points)
selected Aug 30 by Daniel Zwiener
I thought it might be an inner class! I discussed this with Professor Mueller since we had just begun learning about inner classes. Thank you!
+2 votes
I did some experimenting and I think I figured it out. Java allows you to override methods for a particular instance of a class. All you have to do is drop two brackets after the parenthesis and put the desired method(s) in, and that instance will run the new method instead of the one the class normally runs. Whats going on here is that you're passing a modified instance of the TimerTask class as a parameter for the Timer object.
answered Aug 29 by Ryan Philp (727 points)
You're on the right track, but that's not exactly correct!