aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Having doubt on static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Having doubt on static " Watch "Having doubt on static " New topic
Author

Having doubt on static

Rajesh k Jha
Ranch Hand

Joined: May 10, 2009
Posts: 72
In the code given i just want to know that whenever i call any method
from the public static void main() it must be static or not,
As it has created some confustion, So far as i have read we cant call
any non-static method or variable from static method..Please elaborate this part

class TestThread extends Thread{
public void restart()
{
startMe();
}
public static void startMe()
{
// Some magic code here
}
public static void main(String[] args)
{
TestThread t1=new TestThread();
t1.start();
t1.restart();
}
}
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9280
    
  17

Rakesh, you can call any non-static methods or fields from static methods (like main) but you need an instance of the class to do that. You can't access non-static members from a static method directly.

Also please Use Code Tags when you post a source code...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1

You can call static method using the full qualified name:

ClassName.methodName(...)

or using the instance of the class:
new ClassName().methodName();

When you invoke method from within the main method that method must be static if you do not have the instance of the enclosing class.


SCJP6, SCWCD5, OCE:EJBD6.
BLOG: http://leakfromjavaheap.blogspot.com
 
 
subject: Having doubt on static
 
Similar Threads
Thread Question
lock on Classname.class?
Thread
Threads
Threads