1

While surfing,I got through a thing which confused me ,

Thread x=new Thread()
{
 void run()
 {
   //some code 
 }
};

Was wondering how can we directly use run method with this object making,what's the benefit of doing this and can we define a any method with any object,or we have to override a method,I am simply confused what's happening here.Please help me out

user3239652
  • 775
  • 2
  • 9
  • 23

2 Answers2

3

Its an anonymous thread class

You're already creating an instance of the Thread class - you're just not doing anything with it. You could call start() without even using a local variable:

Thread x = new Thread() {
    public void run() {
        System.out.println("something");
    }
};
x.start();

Go throught this question for more info link

Community
  • 1
  • 1
Zeeshan
  • 11,851
  • 21
  • 73
  • 98
0

That is called "creating an annonymous instance based on an existing class". Basicaly you create a new object instance of type Thread and you also override (in that case) the run() method. The advantage is that you don't have to declare a new class in a new file. Its a quick way to get an instance and modify it on the spot (override). You can't however reuse this instance template like you would with a normal class (that would extend Thread).

Vasile
  • 134
  • 2