Static is a keyword used quite frequently in Java, let's summarize its usage, and comb your knowledge tree.
First, static variables:
Static variables have only one copy in memory, the JVM allocates only one memory at a time, and the memory allocation of static variables is done during class loading.
instance variable, without creating an instance, allocates memory for the instance variable once, and the instance variable can have multiple copies in memory and does not affect each other.
The initialization order of static member variables is initialized in the order in which they are defined.
Second, the static method:
The first thing to make clear is that the variables, methods, blocks of code modified by static are loaded directly into memory in the JVM, that is, they are the first part of the program to be run. And this time, the instance of the class that it belongs to May also
is not created, so it is not difficult to understand that static methods cannot be used with the This and Super keywords, cannot directly access the instance variables and instance methods of the owning class (that is, member variables without static and member member methods), and can only access the static of the owning class
State member variables and member methods.
Third, static code block:
A static block can be placed anywhere in the class and can have more than one static block in the class. When the class is first loaded, each static block is executed in the order of the static blocks and is executed only once. So the static block can be used
To optimize program performance.
Four, static import:
Define a class person that contains a static member first.
1 Package Org.gloria.demo; 2 3 Public class person{4 Public Static Final int Age=20; 5 Public Static Final String sex= "Male"; 6 }
When used in another package, if you do not use static import, it is the following notation:
1 PackageOrg.gloria.demo22 ImportOrg.gloria.demo.Person;3 4 Public classfamily{5 6 Public Static voidMain (stirng[] args) {7 8 intA=Person.age; 9 Ten } One A}
Using static imports, this is what it looks like:
Package Org.gloria.demo2 Import Public class family{ publicstatic void Main (stirng[] args) { int a= age ; }}
Five, static internal class:
About the inner class, after a single article, now mention a few points of attention:
A static member cannot be declared in a non-static inner class.
Static inner classes cannot access non-static member variables and methods of their external classes.
Usage collation of static in Java