The static keyword in Java is primarily used for memory management (yes, you heard it wrong). We can apply it to variables, methods, blocks of code, nested classes, and import packages. A static keyword belongs to a class, not an instance of a class.
1. Static variables
- A static variable can be considered a common property for all objects, such as the employee's company name, the student's school name
- Static variables get memory in the method area (class zone) only when the class is loaded
Pros: Save memory 2. Static methods
- Static methods belong to classes rather than objects of classes
- A static method can be called without an instance of a class, with the implication that a static method can be called by a class, and can naturally be called by a class object.
- Static methods can access static data members and change their values
Limitations: There are two main limitations
- Static methods cannot use non-static data members or call non-static methods directly
- The this or Super keyword cannot be used in a static context because they do not implicitly accept the This parameter
Q&a: Why is the main method of Java static?
Because calling a static method does not require an object. If the main method is a non-static method, the JVM needs to create an object before invoking the main method, which results in additional memory allocations
3. Static code block
- Static blocks of code are used to initialize static data members
- Static code blocks are executed before the main method is loaded, and can be compared to the execution time of the instance Initalizer block
Q&a: Can we execute a program without the Main method?
No way. The only way before JDK1.6 is to use static blocks of code, but since JDK1.7, he cannot be executed without the main method.
4. Static Inner class
- Static inner classes can use static data members and methods of external classes, but not non-static data members and methods. Unlike non-static inner classes, all data members and methods of an external class can be used
- Static inner classes are commonly used in build mode
5. Static Guide Package
- You can write fewer prefixes to make your code more beautiful.
- Do not recommend using
Java Static keyword