• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

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.
 
Do you want ants? Because that's how you get ants. And a tiny ads:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic