![]() |
Call the class main function
I define a class and write the main method without static. I can compile it. But in other class when I initiate one instance of that class (call it aa) and call aa.main(args); (with args the correct input type), I got an error "variable aa might not have been initialized.
I understand that main is called when it is executed. Then does that mean public static is the only way all the main functions can be, at least meaningfully? |
Quote:
First, it needs to have the same 'signature', or argument list. This is so the Java VM knows what parameters to use when calling it. Second, and more importantly, it needs to be static so that the VM can call it without first creating any class instances. Non-static methods can only be called using an object of the class. Since the VM won't create classes until you tell it to (barring some startup classes it might create for its own use), you won't have an object to use before main() is called, and thus, it must be a static method. Having said all that, there is no absolute requirement that a given class have a main() method in the given format, or even a main() method at all. Instead, only the class that is the entry point for your application needs such a method. |
Please post what you have so far. Also, include the line number of where the error occurs.
|
Quote:
:
public class test2{and :
public class test1{test2.java can be compiled but not executed. When test1.java is compiled, the error is what I just posted in my first post. |
Quote:
|
lectricpharaoh has explained this very well, so I won't go into detail. To put it simply, when you run your Java application, the interpreter looks for a main method which must have the exact signature, public static void main(String[] args). This method will be the entry point for your program; any similar methods (eg, without the "static" keyword) will be treated as ordinary methods.
As for your example code, the reason it does not run has nothing to do with the naming of your methods. Since you have omitted the "static" keyword in the method main() in the test2 class, it is treated as an ordinary method. The errors you are experiencing arise from not having initialized the class or array variables; remember that all variables in Java are references. :
public class test1{ |
you can call main like this
:
class MyClassIts static so that there does not have to be an instance of MyClass to call main. Static method and fields are never part of a instance of that class, but are always there if you call them by the class name. So you could have a static variable that keeps track of the number of instances of that class by incrmenting it in the constructor and decrementing it in the finalize method. |
| All times are GMT -5. The time now is 1:54 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC