Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Having doubt on static

 
Rajesh k Jha
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9529
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic