Java static 关键字

Java 中的 static 关键字是什么?

在 Java 中,如果我们想要访问类成员,我们必须先创建一个类的实例。但是,有时我们希望在不创建任何变量的情况下访问类成员。

在这些情况下,我们可以在 Java 中使用 `static` 关键字。如果我们想在不创建类实例的情况下访问类成员,我们需要将类成员声明为 static。

Java 中的 `Math` 类几乎所有的成员都是 static 的。所以,我们可以访问它的成员而不创建 Math 类的实例。例如,

public class Main {
    public static void main( String[] args ) {

        // accessing the methods of the Math class
        System.out.println("Absolute value of -12 =  " + Math.abs(-12));
        System.out.println("Value of PI = " + Math.PI);
        System.out.println("Value of E = " + Math.E);
        System.out.println("2^2 = " + Math.pow(2,2));
    }
}

输出:

Absolute value of -12 = 12
Value of PI = 3.141592653589793
Value of E = 2.718281828459045
2^2 = 4.0

在上面的示例中,我们没有创建 `Math` 类的任何实例。但是我们仍然可以访问它的方法:`abs()` 和 `pow()` 以及变量:`PI` 和 `E`。

这是可能的,因为 `Math` 类的所有方法和变量都是 static 的。


Static 方法

Static 方法也称为类方法。因为它是一个 static 方法属于类而不是类的对象。

我们可以直接使用类名调用 static 方法。例如,

class Test {
    // static method inside the Test class
    public static void method() {...}
}

class Main {
    // invoking the static method
    Test.method();
}

在这里,我们可以看到,我们可以直接使用类名从其他类访问 static 方法。

在每个 Java 程序中,我们都将 `main` 方法声明为 `static`。这是因为要运行程序,JVM 应该能够在没有内存中任何对象存在的情况下,在初始阶段调用 main 方法。

示例 1:Java static 和非 static 方法

class StaticTest {

    // non-static method
    int multiply(int a, int b){
        return a * b;
    }

    // static method
    static int add(int a, int b){
        return a + b;
    }
}

public class Main {

   public static void main( String[] args ) {

        // create an instance of the StaticTest class
        StaticTest st = new StaticTest();

        // call the nonstatic method
        System.out.println(" 2 * 2 = " + st.multiply(2,2));

        // call the static method
        System.out.println(" 2 + 3 = " + StaticTest.add(2,3));
   }
}

输出:

2 * 2 = 4
2 + 3 = 5

在上面的程序中,我们在 `StaticTest` 类中声明了一个名为 `multiply()` 的非 static 方法和一个名为 `add()` 的 static 方法。

在 `Main` 类中,我们可以看到我们通过类的对象(`st.multiply(2, 2)`)调用非 static 方法。但是,我们通过类名(`StaticTest.add(2, 3)`)调用 static 方法。


Static 变量

在 Java 中,当我们创建类的对象时,每个对象都会拥有该类的所有变量的自己的副本。例如,

class Test {
    // regular variable
   int age;
}

class Main {
    // create instances of Test
    Test test1 = new Test();
    Test test2 = new Test();
}

在这里,test1 和 test2 这两个对象都会有 age 变量的独立副本。而且,它们彼此之间是不同的。

但是,如果我们声明一个 static 变量,类的所有对象都共享同一个 static 变量。这是因为,与 static 方法一样,static 变量也与类相关联。而且,我们不需要创建类的对象来访问 static 变量。例如,

class Test {
    // static variable
    static int age;
}
class Main {
    // access the static variable
    Test.age = 20;
}

在这里,我们可以看到我们通过类名从其他类访问 static 变量。

示例 2:Java static 和非 static 变量

class Test {

   // static variable
   static int max = 10;
  
   // non-static variable
   int min = 5;
}

public class Main {
   public static void main(String[] args) {
       Test obj = new Test();

       // access the non-static variable
       System.out.println("min + 1 = " + (obj.min + 1));

       // access the static variable
       System.out.println("max + 1 = " + (Test.max + 1));
   }
}

输出:

min + 1 = 6
max + 1 = 11

在上面的程序中,我们在 `Test` 类中声明了一个名为 `min` 的非 static 变量和一个名为 `max` 的 static 变量。

在 `Main` 类中,我们可以看到我们通过类的对象(`obj.min + 1`)调用非 static 变量。但是,我们通过类名(`Test.max + 1`)调用 static 变量。

注意:Java 中很少使用 static 变量。相反,使用了 static 常量。这些 static 常量由 `static final` 关键字定义,并用大写字母表示。这就是为什么有些人宁愿将 static 变量也用大写字母表示。


在类中访问 static 变量和方法

我们正在从另一个类访问 static 变量。因此,我们使用了类名来访问它。但是,如果我们想从类内部访问 static 成员,可以直接访问。例如,

public class Main {

   // static variable
   static int age;
   // static method
   static void display() {
       System.out.println("Static Method");
   }
   public static void main(String[] args) {

       // access the static variable
       age = 30;
       System.out.println("Age is " + age);

       // access the static method
       display();
   }
}

输出:

Age is 30
Static Method

在这里,我们可以直接访问 static 变量和方法,而无需使用类名。这是因为 static 变量和方法默认是 public 的。而且,由于我们是从同一个类访问的,所以不需要指定类名。


Static 块

在 Java 中,static 块用于初始化 static 变量。例如,

class Test {
    // static variable
    static int age;

    // static block
    static {
        age = 23;
    }
}

在这里,我们可以看到我们使用了具有以下语法的 static 块

static {
    // variable initialization
}

当类加载到内存中时,static 块仅执行一次。如果在代码中请求类的对象,或者在代码中请求 static 成员,类就会被加载。

一个类可以有多个 static 块,每个 static 块都按照它们在程序中的编写顺序执行。

示例 3:Java 中 static 块的用法

class Main {

   // static variables
   static int a = 23;
   static int b;
   static int max;

   // static blocks
   static {
       System.out.println("First Static block.");
       b = a * 4;
   }
   static {
       System.out.println("Second Static block.");
       max = 30;
   }

   // static method
   static void display() {

       System.out.println("a = " + a);
       System.out.println("b = " + b);
       System.out.println("max = " + max);
   }

   public static void main(String args[]) {
       // calling the static method
       display();
   }
}

输出:

First Static block.
Second Static block.
a = 23
b = 92
max = 30

在上面的程序中。一旦 Main 类被加载,

  • 变量 `a` 的值被设置为 23
  • 第一个 static 块被执行。因此,打印字符串 First Static block,并将变量 `b` 设置为 a * 4
  • 第二个 static 块被执行。因此,打印字符串 Second Static block,并将 `max` 的值设置为 30
  • 最后,执行 `display()` 方法内的打印语句。

嵌套的 Static 类

在 Java 中,我们可以在一个类中声明另一个类。这样的类称为嵌套类。嵌套类分为两种类型:

  • Static 嵌套类
  • 非 static 嵌套类

例如,

class OuterClass {
    // static nested class
    static class NestedClass {...}

    // non-static nested class
    class InnerClass {...}
}

要了解更多信息,请访问 Java 嵌套类

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战