*
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
Author

Construction

Taras Shemberko
Greenhorn

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
Bartender

Joined: Dec 08, 2010
Posts: 1502
    
    5

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.


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

Joined: Oct 13, 2005
Posts: 37982
    
  22
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
 
Similar Threads
Timer & TimerTask - Name of Timer Object
What does this thread do please?
Timer
Beginner game
What is the Linux command to find the created timer daemon