• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

this and static method

 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class ThreadTest extends Thread {
public void run() {
System.out.println("Before sleep");
try {
this.sleep(1000);
}
catch (InterruptedException ie) { }
System.out.println("After sleep");
}

public static void main(String[] args) {
ThreadTest a = new ThreadTest();
a.start();
}
}
The above program compile and run. Can somebody explain why this.sleep(1000) works here? Is it because sleep() is used in the run() method which is non-static?
 
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
"this" in a method means the object that was invoked.
so we can't use "this" in a static method, which applies for the whole class not for an instance.
Vanitha.
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, this.sleep() works because you're invoking it from a non-static method. But you don't really need the "this" because sleep(msec) is itself a static method of class Thread. So you could call it from a static method without using the "this" reference.

Ranjan
 
Bin Wang
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks guys.
In fact, "this" can't be used in a static method. It'll cause compile error.
reply
    Bookmark Topic Watch Topic
  • New Topic