Forums Register Login

Regarding accessing static methods.

+Pie Number of slices to send: Send
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??
+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send
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).
There's a way to do it better - find it. -Edison. A better tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 881 times.
Similar Threads
Calling run method directly
Doubt related to sleep() in Thread
dan exam doubt 20
Basic thread doubt
synchronized threads
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 06:13:52.