开发者

How main method called without calling it by classname.mainmethod() [closed]

It's difficult to tell what is being asked her开发者_JAVA技巧e. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

This is very basic question, many of us didn't know this answer. In java, to call static methods we have to follow this classname.method();. But when comming to main(), its not been called by classname.main() even though it is static.


The best way to understand how "main()" is called by JVM is to see how "java" calls your main method. Here is the JNI example explaining the same.

mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V");
    ...
(*env)->CallStaticVoidMethod(env, cls, mid, args);


Yes it is. The java "interpreter" takes the class name you're giving it, looks for a static main method taking a String array as argument and returning void, and calls this method. The java interpreter probably does this using native code, but that's not important.

If, inside a program, you want to call another class's main method, you can. main methods are not special in this regard. The only special thing they have is that they can be the entry point for the java interpreter.


The main method is invoked by the java interpreter itself when you run the class, without have to add the class names. you can find more detail explaination @ Why is the Java main method static?


You can call static methods in Java as though they were instance methods but this is considered bad practice.

public class Foo {
    public static void bar() { ... }
}

...
Foo foo = ...
foo.bar(); // this will work
Foo.bar(); // but this is better


It's being called with Class.main() as you have to provide the class containing a main() method, when starting an application.


But when comming to main(), its not been called by classname.main() even though it is static.

How can you say so? I am afraid you have got it wrong.
You can call a static method using object,though.

Usually you never call main yourself.It is an entry-point for your program and JVM calls it to start the execution of the program.
Also this is the reason you need to pass the name of the class when you execute your code.
Remember this:

java ClassName

This is how you execute your program from command line. ClassName here is the name of your Class having the main method.

This class name is used by JVM to call your main method e.g, ClassName.main()

And all this calling stuff is done using native code C/C++.You might want to google it, in case you want to know exactly how all this works.
If this is not exactly what you were looking for, maybe you can explain the question little more.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜