Preface
static
, this tiny keyword plays a big role in Java, but its purpose and working can be confusing. Have you ever wondered why some methods and variables can be accessed directly from the class without creating an instance? Or why do some variables share the same value between multiple instances? In this article, we will explorestatic
The secret of the process, diving into its various usages, from the call to static methods to the sharing of static variables, letting you get to the Javastatic
Have a clear understanding.
First: Static method
Static method(Static Method) is a method that belongs to an instance of a class, not a class. It can be called without creating an instance of the class. Static methods are often used to perform class-related operations without accessing or modifying the state of a specific instance.
Here is the difference between declarations, calls and instance methods of static methods:
Declare static methods:
In Java, declaring static methods requires usestatic
Keywords. Static methods can directly belong to a class, not an instance of a class.
public class MyClass { public static void myStaticMethod() { // Code of static method } }
Calling static methods:
You can call static methods by class name without creating instances of the class.
();
The difference between static methods and instance methods:
Relevance: Static methods are related to the class itself, while instance methods are related to instances of the class.
Call method: Static methods are called through class names, while instance methods need to be called through object instances.
Access permissions: A static method can access static members of a class, but cannot access non-static members (instance members). Instance methods can access both static and non-static members of a class.
Internal citations: Cannot be used in static methods
this
keyword, because it has no reference to the current object. The instance method can be usedthis
to reference the current object.life cycle: Static methods are initialized when class loads, while instance methods are initialized when object creation.
In short, static methods are methods related to the class itself, and are often used to perform general operations or access static members. An instance method is a method related to an instance of a class, which can access and modify the status of an instance. Choosing to use a static method or an instance method depends on your needs and code design.
Second: Static variables
Static variables, also known as class variables, are variables that belong to an instance of a class rather than a class. It is initialized when the class is loaded, with only one copy, and is shared by instances of all classes. Static variables are often used to store class-level data, which do not depend on the state of a specific object, but are associated with the entire class.
Here is information about the declaration, use, life cycle, and scope of static variables:
Declare static variables:
In Java, declaring static variables requires usestatic
Keywords. Static variables are usually located at the top of the class, usually declared inside the class, outside the method. Static variables are usually usedpublic
, private
, orprotected
etc. Modifiers are modified.
public class MyClass { // Static variable declaration public static int staticVariable; private static String name; }
Using static variables:
You can access static variables through class names, or you can access them through instances of the class. It is often recommended to use class names to access static variables because they are associated with classes, not with specific object instances.
= 42; // Access static variables through class nameint value = ; // Get the value of the static variable through the class name MyClass myObject = new MyClass(); = 10; // Static variables can also be accessed through object instances
Lifecycle of static variables:
The life cycle of a static variable is the same as that of a class. They are initialized when the class is loaded and exists until the program ends or the class is unloaded. The values of static variables remain unchanged after class loading because they are class-level and not associated with object instances.
Scope of static variables:
Static variables are visible throughout the class, and their scope covers the entire class. Static variables can be accessed inside or outside any method of the class.
In short, static variables are variables that belong to the class, not instances of the class. They are initialized at class loading, have a global scope, and are used to store class-level data. Static variables are usually used to store information that does not depend on specific object instances, such as constant values, counters, etc.
Third: Static blocks
Static initialization blockIt is a special block in Java that is used to perform static initialization operations when class loads. Static initialization blocks are usually used to perform some initialization tasks related to static member variables, or to perform some necessary settings when the class is loading.
Here is information about the purpose of a static initialization block and how to use it to initialize a static variable:
Uses of static initialization blocks:
Initialize static variables: Static initialization blocks can be used to initialize static variables, usually when the initial value of static variables cannot be directly assigned.
Execute complex initialization logic: If the initialization of static variables requires complex logic or depends on the loading of other classes, these operations can be performed in the static initialization block.
Resource Management: Static initialization blocks can be used to manage resources such as initialization and release of database connections or file handles.
How to initialize static variables with static blocks:
In Java, you can use static initialization blocks in a class, whichstatic {}
The form definition contains the initialization code.
public class MyClass { // Static variable declaration public static int staticVariable; // Static initialization block static { // Perform initialization operation staticVariable = 42; } }
In the above example, the static initialization block is executed when the class is loaded and the static variable is initializedstaticVariable
The value is 42. Static initialization blocks allow you to execute more complex logic, such as initializing static variables based on conditions, performing multi-step initialization, etc.
Note that the static initialization block is only performed once when the class is loaded, so it is suitable for one-time initialization operations. If you have multiple static initialization blocks, they will be executed in the order in the class.
Fourth: Static inner class
Static inner classis a class nested in another class, but it is a static class that has nothing to do with instances of the external class. A static inner class can be instantiated without creating an external class instance and can access static members of the external class, but cannot access non-static members of the external class.
The main features of static internal classes include:
- It is declared static (using
static
keyword). - It cannot access non-static members (i.e. instance members) of an external class.
- It can access static members and methods of external classes.
- Instantiation of static inner classes does not depend on instances of external classes.
Uses of static internal classes:
Static inner classes are often used in the following situations:
Package: Encapsulate a set of related classes inside a class to reduce naming conflicts and improve the organization and readability of the code.
Factory model: Static inner classes can be used to implement factory pattern, where external classes act as factories, and static inner classes act as factory methods.
Singleton mode: Static inner classes are often used to implement lazy loading singleton patterns because they are loaded and initialized when needed.
Optimize class structure: Organize some classes that are not directly associated with external classes but have some connection to them to reduce the number of classes and improve code maintainability.
Example:
Here is an example showing how to use static inner classes:
public class OuterClass { private static int outerStaticVariable = 42; // Static inner class public static class StaticInnerClass { public void printOuterStaticVariable() { ("Outer static variable: " + outerStaticVariable); } } public static void main(String[] args) { // Create an instance of a static inner class StaticInnerClass inner = new StaticInnerClass(); (); } }
In this example,StaticInnerClass
is a static inner class that can access external classesOuterClass
Static members ofouterStaticVariable
, but not accessing non-static members. This allows you to organize relevant classes together and improves the readability of your code.
Fifth: Static import
Static importis a feature in Java that allows you to directly refer to static members of a class in your code without explicitly specifying the class name. The main purpose of static import is to simplify the code, improve readability, and reduce duplicate class name references.
Purpose and usage scenarios of static import:
Simplify the code: Static import can simplify the code, especially when you frequently use static methods or constants of a certain class, saving you the hassle of repeatedly entering the class name.
Improve readability: Through static import, you can express the intent of the code more clearly, reduce the lengthy class name prefixes, and improve readability.
Avoid naming conflicts: In some cases, static imports can also help avoid naming conflicts, as you can selectively import the required static members without polluting the namespace.
How to simplify code using static import:
Suppose there is a nameMathUtil
class containing some static methods and constants:
public class MathUtil { public static int add(int a, int b) { return a + b; } public static final double PI = 3.14159265359; }
Using static import, you can directly reference these static methods and constants in your code without explicitly specifying the class name:
import static .*; public class Main { public static void main(String[] args) { int result = add(5, 3); // No need to write double circleArea = PI * 5 * 5; // No need to write ("Result: " + result); ("Circle Area: " + circleArea); } }
In the above example, useimport static
The statement has been importedMathUtil
The static methods and constants of the class make theMain
They can be used directly in the class without writing the class name prefix.
It should be noted that you should try to avoid abuse of static imports and import only necessary static members to ensure the readability of the code.
Sixth: Singleton Mode
Singleton modeis a creative design pattern that ensures that a class has only one instance and provides a global point to access that instance. Singleton pattern can be easily implemented using static variables.
Here is an example code for how to implement a singleton pattern using static variables:
public class Singleton { // Use static variables to store singleton instances private static Singleton instance; // Private constructor method to prevent external instantiation private Singleton() { } // Public static method for obtaining singleton instances public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
In the above code,Singleton
The constructor of a class is private, which means that the external class cannot instantiate it directly. BygetInstance
Methods, you can getSingleton
A single instance of the class. This instance is through static variablesinstance
The storage is only in the first callgetInstance
Methods are created only when they are created. The same instance will be returned in the future.
Thread safety issues and solutions:
The above singleton pattern example is the basic singleton pattern, but it is not thread-safe. When multiple threads access simultaneouslygetInstance
When a method is used, multiple instances may be created. To ensure thread safety, there are several solutions:
-
Hungry Man-style single case(Eager Initialization): Create singleton instances when the class is loaded to ensure thread safety, but may lead to waste of resources.
public class Singleton { private static final Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; } }
-
Double check lock(Double-Check Locking): Locking is added when the instance is acquired for the first time, and subsequent accesses do not require locking, which improves performance.
public class Singleton { private static volatile Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized () { if (instance == null) { instance = new Singleton(); } } } return instance; } }
-
Static inner class: Use static inner classes to delay loading singleton instances and use class loading mechanism to ensure thread safety.
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton() { } public static Singleton getInstance() { return ; } }
These are some common thread-safe implementations of singleton patterns. Which method to choose depends on the project's requirements and performance considerations. The most commonly used are double check locking and static inner class methods, both of which are thread-safe and delayed loading.
Seventh: Frequently Asked Questions and Best Practices
Lifecycle and thread safety of static members, avoiding abusestatic
Best practices and naming specifications for static variables are key issues to consider when writing high-quality Java code. Here are detailed explanations and best practices for these issues:
Lifecycle and thread safety of static members:
life cycle: Static members are initialized when the class is loaded, with the life cycle the same as the application's running time. They will only be initialized once.
Thread safety: Static members are shared globally, so there may be thread safety issues. If multiple threads access and modify static members at the same time, you need to take appropriate measures to ensure thread safety, such as using synchronization or other concurrency control mechanisms.
Avoid abusestatic
Best Practices:
Unnecessary static: Avoid overuse of static members in classes. Data should be defined as static only when it needs to be shared by all instances of the class. Avoid declaring each member as static, which results in unnecessary global state.
Cautionary use of global variables: Avoid excessive use of static variables as global state. Global variables can make code harder to understand, debug, and maintain. Try to limit the scope of the variable to the minimum required range.
Smart use of static methods: Static methods are usually used in utility classes, factory methods, singleton patterns, etc., but should not be abused. Make sure they are used reasonably, rather than defining all methods as static for convenience.
Naming specifications for static variables:
The naming of static variables is usually capitalized and separated by underscores between words to increase readability. For example:
MAX_VALUE
,DEFAULT_TIMEOUT
.Static variables should be constant and should not change their values at runtime. If static variables need to be modified, they will usually be used
final
Keyword declaration.Static constants (such as enumerations) are usually made with all capital letters and underscores between words to indicate that they are immutable. For example:
RED
,GREEN
.
In short, the life cycle of static members is the same as class loading, and thread safety needs attention. Avoid abusestatic
, only if necessary. When naming static variables, follow the naming specifications, using capital letters and underscores for greater readability.
Eighth: Case Study
In actual projects,static
Keywords are often used in various scenarios, here are some examples of how to use them in real projectsstatic
:
-
Constant definition:
static
Constants are often used to define invariant constants to avoid magical numbers and improve code readability. For example, in a geometric calculation library, you can definestatic final
Constant to represent pi:public class MathConstants { public static final double PI = 3.14159265359; }
-
Tools: Static methods and static variables are commonly used in tool classes that provide a set of static methods to perform general tasks. For example,
All methods in the class are static and are used to perform mathematical operations.
double result = (16.0); // Call static methods
-
Singleton mode: Static variables are often used to implement singleton patterns to ensure that there is only one instance of the class. In a singleton class, there is usually a private static variable to store a singleton instance.
public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
-
Static inner class: Static inner classes are often used to implement singleton patterns for lazy loading, which acts as a factory and implements lazy loading.
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton() { } public static Singleton getInstance() { return ; } }
-
Static factory method: Static factory methods are usually used to create object instances instead of using constructors. For example,
Classes provide many static factory methods for creating immutable collections.
List<String> unmodifiableList = (originalList);
-
cache: Static variables can be used to cache data for improved performance. For example, you can use static
Map
to cache the calculation results to avoid repeated calculations.public class MathCache { private static Map<Integer, Double> squareRootCache = new HashMap<>(); public static double getSquaredRoot(int number) { if (!(number)) { double result = (number); (number, result); } return (number); } }
These examples show how to use them in real projectsstatic
Common scenarios for keywords include defining constants, creating tool classes, implementing singleton patterns, implementing static internal classes, providing static factory methods, and using caches.static
Helps provide global state, improve performance and provide tooling methods in these scenarios.
Summarize
This is the end of this article about static static variables and static methods in Java. For more related contents of static static variables and static methods in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!