• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding accessing static methods.

 
Ravi Kumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Demo implements Runnable
{
public static void main(String args[])
{
//Create the object of Demo class.
Demo obj1 = new Demo()
Thread t1 = new Thread(obj1);
t1.start();
try
{
t1.sleep(1000);
}
catch(InterruptedException e)
{}
}

This code works.
Question : Even if sleep() method is static,we are accessing it via object of the class.why??
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is legal to call a static method via a reference to an instance. However, it is bad practice to do so, as it looks like an instance method call.

Just move on. Nothing interesting to see!
 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Adding to the excellent previous reply:
As a programming teacher, I find that java newcomers are very confused by 'sleep()' method.
It is important to note that the thread going to sleep would be 'main' thread, and not t1...


You can test it by putting some infinite printing loop in both 'Demo' and 'main' (in main, it has to be after the 'sleep' connamd).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic