How to create a static class in Java?

In Java, a static class (also known as a utility class) is a class that only contains static methods and variables. Static classes are typically used to provide common utility methods that can be directly called in other classes without needing to create an instance of that class.

以下是创建静态类的步骤:

  1. Create a new Java class named StaticClass (you can name it according to your actual needs).
public class StaticClass {
    // 静态变量
    public static int staticVariable = 10;

    // 静态方法
    public static void staticMethod() {
        System.out.println("This is a static method.");
    }
}
  1. Define static variables in a class. Static variables are shared among all instances of the class and can be accessed directly via the class name.
public static int staticVariable = 10;
  1. Define a static method within a class. Static methods can be called directly through the class name without needing to create an instance of the class.
public static void staticMethod() {
    System.out.println("This is a static method.");
}
  1. Call static variables and methods from other classes. You can access static variables and call static methods using the class name.
public class MainClass {
    public static void main(String[] args) {
        // 访问静态变量
        System.out.println(StaticClass.staticVariable);

        // 调用静态方法
        StaticClass.staticMethod();
    }
}

Note: Static classes cannot be instantiated because they do not have a constructor. The methods and variables within a static class should also be static, allowing access without the need to create an instance of the class.

bannerAds