开发者

java main function

public static voi开发者_开发知识库d main() & public void main() What is the difference between these two?


The former is (potentially) an entry point method (if it has a String[] argument). The latter is not.

The rule is that an entrypoint method must have the signature:

public static void main(String[])

If we ignore the question of "entrypointness", then the difference between a "static" method and a normal method is as follows:

  • A normal method can only be invoked on a target object, but it can access the instance variables of the target object via explicit or implicit use of this.

  • A static method is not invoked on a target object, and cannot access instance variables via this.


Static functions belong to the class (that is, they use no instance variables (object variables)).


public static void main(String[] args)

Because it uses the special 'main' name and is also static with string arguments, it is the entry point into your program. It can be called like this

YourClass.main(new String[] {"hello"})

However, when you compile you program into a runnable .jar file java will automatically know to run this method. It is the starting point of your program.

In the terminal you will run it like this

java -jar YourClass.jar hello

Other methods can also be made static

public static void myOtherFunction()

The difference here is that myOtherFunction() is NOT the starting point of the application but can be used anywhere in your application that you main need it, you also don't need an instance of a class to use it.

public void main()

Is a normal methods of a class It needs an instance to be able to use it.

YouClass me = new YouClass();
me.main();

Don't ever call any method main() without it being of the signature

public static void main(String[] args)

ie. the entry point of the application. This could potentially be confusing for people reading your code.


Static means that the function does not need a class instance in order to be called.


It's simple: the former main is static (and p in lowercase ;-P)

And the meaning is obvious: ensuring the entrypoint exists before the rest, and tell the framework where the entrypoint is.


Actually static allows only one instance of he main function to be initialized. All static methods can be called without creating an instance of that class. Its global. Main is always delcared static.


varargs version:

public static void main(String... args) {

    for (String arg : args) {
        System.out.println("Argument: " + arg);
    }
}

Available since Java 5.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜