What does static in java mean?

My GitHub
In Java, staticit is a keyword used to indicate that a member (variable, method, nested class, etc.) belongs to the class, rather than belonging to a specific instance of the class. In short, staticmembers are at the class level, not the instance level. Here are some uses staticof the keyword:

static variable

A staticvariable is associated with a class, not an instance. All instances of this class share the same staticvariable.

class MyClass {
    
    
    static int staticVar = 0;
}

static method

A staticmethod belongs to the class, not to any specific instance. Therefore, it cannot access non- staticmembers of the class.

public class HelloWorld {
    
    
    static void sayHello() {
    
    
        System.out.println("Hello, World!");
    }
}

static block

staticBlock is used to initialize staticvariables, which is only executed once when the class is loaded.

class MyClass {
    
    
    static int staticVar;
    
    static {
    
    
        staticVar = 10;
        System.out.println("Static block executed");
    }
}

static inner class

You can also define an staticinner class that cannot access non-members of the outer class static.

public class OuterClass {
    
    
    static class StaticNestedClass {
    
    
        // body of static nested class
    }
}

Why use static?

  1. Sharability : Use staticvariables to share data between all instances. This is typically used for constants or configuration data.
  2. No instances required : staticmethods and variables can be accessed and modified before any instances are created.
  3. Tool methods : staticoften used to store tool methods that do not depend on instance state (such as Math.abs()).
  4. Saves memory : Since staticthe data is not part of each instance, using staticcan save memory.

Precautions

  • Use caution when using staticthe keyword because staticvariables are shared across all instances, which can lead to errors that are not easily traceable.
  • Since staticmethods cannot access non- staticmembers, they cannot be overridden by subclasses.

Overall, statica very useful keyword but one that needs to be used with caution. Understanding how it works and applicable scenarios is very important for Java programming.

Guess you like

Origin blog.csdn.net/m0_57236802/article/details/132992422