04-23.eri-test Java主要方法:为什么有那么多单词?

\n

public static void main(String[] args){
\n// code
\n}

\n\n

\n\n

"Seriously? I have to type this every time i write a program? That is a lot and I miss JavaScript! \xf0\x9f\x98\xad" These were always my thoughts when I was in college just starting with Java after learning JavaScript for a bit.

\n\n

What we see above is the main method in Java. Let\'s break it down and talk about each word in this line of code.

\n\n

Public
\nPublic in Java is an access modifier. Access modifiers specify the accessibility or scope of a method, constructor, or a class. There are four access modifiers:

\n\n
  1. \n
  2. Private: the access level of this modifier is only within the class and cannot be accessed from outside of the class. \n
  3. Public: the access level of this modifier is everywhere and can be accessed within the class, outside the class, within the package and outside the package.\n
  4. Protected: the access level of this modifier is within the package and outside the package through child classes, without which it cannot be accessed from outside. \n
  5. Default: the access level of this modifier is only within the package, and cannot be accessed from outside the package. \n
\n\n

The main method has to be public because we want access to it.

\n\n

Static
\nIn Java, a static member of a class is a member that isn\'t associated with an instance of a class. This member belongs to the class itself and can be accessed without first creating a class instance. A method that is declared with the static keyword is associated with the class itself, and therefore we don\'t have to create an object from a class before using static methods defined by the class.

\n\n

If the main method is not static, JVM wouldn\'t be able to call it because there is no class object present. That\'s why the main method must be static so that JVM can call the main method which is not associated with an instance of a class.

\n\n

Void
\nThis one is simple. The keyword void is used at method declaration to indicate that the method should not have a return value, and this is why main method is void

\n\n

Main
\nMain is just a name for the method, and when we run a Java program, it looks for the name.

\n\n

Below is a simple program that calculates the Fibonacci of n recursively and prints out the result.

\n\n\n
\n \n
\n\n\n\n

你可能感兴趣的:(java,javascript)