static keyword role
1, the static member variable of the specific syntax
2, the static function of the specific syntax
3, static code block specific grammar
Define static member variables
Person.java
class Person{ static int a; }
It can be invoked under the previous
public class Test1{ public static void main(String[] args){ Person person = new Person(); person.a = 10; System.out.println(person.a); } }
The output 10.
After the static could be so coupled with the use of:
public class Test1{ public static void main(String[] args){ Person.a = 10; System.out.println(Person.a); } }
The output 10.
Difference between ordinary members and static member variables of an object
Ordinary member variables corresponding to p1 and p2 independently of each other. The static member variables, p1 and p2 using the same variable.
Static function
Static functions can not directly reference the non-static member variables, this can not be used in static functions.
Define a static function
Person.java:
class Person{ static void fun(){ System.out.println("static function"); } }
Test1.java
public class Test1{ public static void main(String[] args){ Person.fun(); } }
Output: static function
Static code block
Static block of code is executed when the class is loaded, the initial effect is variable.
static{ System.out.println("static code"); }