File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Construction Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Construction" Watch "Construction" New topic


Taras Shemberko

Joined: Feb 20, 2012
Posts: 2
Hi guys!!!
I don't understand this construction:

I understand in this construction someone created new object "timer", but i don't understand what he did after created object.
Please explain me this construction
Anayonkar Shivalkar

Joined: Dec 08, 2010
Posts: 1545

Hi Taras Shemberko,

Welcome to CodeRanch!

Its good that you've used code tags, however, make sure to execute code at local machine before posting it. e.g. the code given by you is having 2 issues:
1) Typo error in InterruptedException ('c' is missing in Exception )
2) Since try block is empty, there's no code inside it which will throw an InterruptedException. Hence, another compile time error would be - unreachable catch block. A good practice is to catch only those exceptions which can be thrown by try block.

That apart, lets come to the code snippet (assuming that all compile time errors are resolved).

This style of construction is called as anonymous subclass, or inner class (btw, are they same? ). Here, what exactly you are trying to do is - create a new class, which is a sub-class of Thread. The new class does not have any name. Now, in that new class, you've overridden run method. Thus, the new class will come into picture only as long as timer object is concerned - i.e. when 'timer' is started, the code of run method would be invoked internally. However, the behavior is specific only to that object. All other Threads will not necessarily have this behavior.

This phenomenon is widely used in UI programming, where each element can have different ActionListener, but since those Listeners are going to be used only for those elements, there's no point in writing a new class and creating an object. So, it can be easily done by anonymous classes.

I hope this helps.

Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46337
Anayonkar Shivalkar wrote: . . . This style of construction is called as anonymous subclass, or inner class . . .
It is an anonymous inner class. In that instance, it is probably local to a method. It creates an object which is an instance of a subclass of Thread.
It is sorta covered in the JavaRanch Style Guide.
subject: Construction
It's not a secret anymore!