Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Envoking Main method from another method.

Status
Not open for further replies.

BillyKrow

Programmer
Aug 27, 2001
67
US
I need to be able to call a classes main method from another classes main method and pass it arguments. Not sure on syntax or if I need to run some sort of separate thread or shell. Any quick examples would be apreciated.
 
main() is just like any other static method and is called as such. Arguments are passed in a String array.

Example:
Code:
//Create parameter list
String[] args = {"Set", "of", "parameters", "."};

//Call main method of Test class (assuming it is public)
Test.main(args);
 
That was actually the first thing I tried but I get an error like "method main not found in class...". The class is imported from another package and I can declare the imported class error free eg. "ClassName test = new ClassName();" But when I try use "test.main(args)" like you suggested, I get the error.
 
Your attempt didn't work because you tried to execute main() on an instance of the class. main() is a static method otherwise known as a Class Method and therefore doesn't belong to any one instance but rather to the class as a whole. This is a common mistake by beginning Java Programmers.

Your Code (Incorrect):
Code:
ClassName test = new ClassName();
test.main(args);

Correct Code:
Code:
ClassName.main(args);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top