As with static variables, we can also use the static modification method, called a static method or a class method. In fact, the main method we've been writing about is static methods. The use of static methods such as:
Operation Result:
Need to note:
1 static members can be called directly in a static method, but not non-static members directly. such as:
if you want to invoke a non-static variable in a static method, you can access the non-static variable by creating the object of the class and then through the object . Such as:
2, in the ordinary member method, you can directly access the same kind of non-static variables and static variables , as follows:
3, static methods can not directly invoke non-static methods, you need to access the non-static method through the object. such as:
Task
Two static variables, score1 and score2, are defined in the editor to hold the score information. Defines a static method sum, which calculates the score score, and outputs the score score in the main method by calling the static method
Please follow the comments to complete the Code 6, 9, 10, and line
Running result: Total score: 178
Public classHelloWorld {//defining static Variables Score1 Static intScore1 = 86; //defining static variables Score2 Static intScore2 = 92; //defines the static method sum, calculates the score score, and returns the total score Public Static intsum () {intsum; Sum= Score1 +Score2; returnsum; } Public Static voidMain (string[] args) {//call the static method sum and receive the return value intAllscore =helloworld.sum (); System.out.println ("Total Score:" +Allscore); }}
Static methods for using static in Java