2015-10-20
Before learning Java knowledge, just follow the code used to jump to learn some, not all of the learning is also wrong into pieces ... Well, what a tragedy!
Reasoning, it is necessary to review and finishing, otherwise written out of things really can't read. So, from today's 1.1-point gnawing down.
Back to the creation of the class file, and see the familiar main function ... Then, there is the question of the title. So, let's review the question today.
1 Public classREVIEW_P2 {2 Public Static voidMain (string[] args) {3 byteb = 3;4 5 byteAA = 4;6 byteBB = 5;7 8 //b = aa + bb;9 //at this point the AA BB is a variable, and cannot determine the range, can not determine whether the precision is lost, so Java will not be assigned a valueTen System.out.println (b); One } A}
Review_p2.java
Generally speaking, the question is raised directly on the Internet, and the reply will be: The Main method must be static, Java is so stipulated. Well, maybe the answer is what we want to get.
Then keep looking:
- Let's look at the effect of static: in a class, a variable modified by the static modifier is called a static variable (also called a class variable), whereas the static method is statically, and the static method belongs to the class and not to an object. So the static method is called directly from the class name without having to create the instance first.
So the main here is the same, the static Main method can be called directly by the JVM, do not have to new out of the instance before execution. Thus, when we compile this Java code, the interpreter is in the current REVIEW_P2 class to call the static Main method, without the need to produce REVIEW_P2 object of this class, when we load the REVIEW_P2 class, The Main method is also loaded as a portal to the Java program.
also note that in a static method, you cannot invoke a non-static method and reference a non-static variable. But in turn, it's no problem.
This is because when a class is loaded, static variables and static methods allocate memory space, and when non-static methods call them, they already have memory space, which in turn is not possible.
Also, see that there are predecessors mentioned before the main () method may not be static, but later the JSR specification enforces the format of the main () method must be: public static void Main (string[] args) {...} , if this is the case, then do it according to the standard, and change it is certainly convenient for you and me his.
Java Basics Review (1) Why in Java do we define main as a static method?