Java-静态块

时间:2020-02-23 14:36:52  来源:igfitidea点击:

在本教程中,我们将学习Java编程语言中类的静态块。

在先前的教程中,我们了解了静态变量和静态方法。
现在我们将讨论静态块。

使用静态块

如果要初始化静态变量,则使用静态块。
加载类时,静态块仅执行一次。

静态块的语法

static {
  //some code...
}

其中," static"关键字用于定义静态块。
大括号" {"标记为静态块的开始,而大括号"}"标记为静态块的结束。

在下面的示例中,我们具有HelloWorld类,并且它具有一个静态整数变量objectCount

我们将首先在静态块中初始化此静态整数变量。

注意!每当创建类的新对象时,此静态整数变量的值就会增加。

我们也有getCount()resetCount()静态方法来分别获取和重置objectCount变量的值。

class HelloWorld {

  //static variable
  static int objectCount;

  //variable
  private int number;

  //static block
  static {
    System.out.println("Inside the static block of HelloWorld class.");
    System.out.println("Initialising objectCount static variable.");
    objectCount = 0;
    System.out.println("Done initialising objectCount static variable of HelloWorld class inside the static block.");
  }

  //constructor
  HelloWorld(int number) {
    this.number = number;

    //updating the static variable
    HelloWorld.objectCount++;
  }

  //static method
  static void resetCount() {
    objectCount = 0;
  }

  static int getCount() {
    return objectCount;
  }

  //method
  public int getNumber() {
    return this.number;
  }
}

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

    System.out.println("Total number of objects of the Hello World class: " + HelloWorld.objectCount);

    //create an object
    System.out.println("Creating object obj.");
    HelloWorld obj = new HelloWorld(10);

    System.out.println("Total number of objects of the Hello World class: " + HelloWorld.objectCount);

    System.out.println("Hello World obj number: " + obj.getNumber());

    //create another object
    System.out.println("Creating object obj2.");
    HelloWorld obj2 = new HelloWorld(20);

    System.out.println("Total number of objects of the Hello World class: " + HelloWorld.objectCount);

    System.out.println("Hello World obj2 number: " + obj2.getNumber());

    System.out.println("Resetting object count of the Hello World class.");
    HelloWorld.resetCount();
    System.out.println("Total number of objects of the Hello World class after reset: " + HelloWorld.getCount());

  }
}
$javac Example.java 
$java Example
Inside the static block of HelloWorld class.
Initialising objectCount static variable.
Done initialising objectCount static variable of HelloWorld class inside the static block.
Total number of objects of the Hello World class: 0
Creating object obj.
Total number of objects of the Hello World class: 1
Hello World obj number: 10
Creating object obj2.
Total number of objects of the Hello World class: 2
Hello World obj2 number: 20
Resetting object count of the Hello World class.
Total number of objects of the Hello World class after reset: 0

第一次加载" HelloWorld"类时,将执行静态块,并将静态整数变量" objectCount"的值设置为0。

在" Example"类内部,我们实例化了HelloWorld类的两个对象。

因此,每次创建HelloWorld类的对象时,在HelloWorld类的构造函数中,使用++增量运算符将静态变量objectCount的值加1。