Java中的静态初始化块

154 阅读4分钟

我们都必须了解 Constructor在Java中。但不同的是,静态初始化块是一组指令,在类加载到内存中时只运行一次。另一方面,构造函数在每次创建一个新的类实例时都会运行。我们将在后面探讨这个问题。

静态初始化块

我们将在这里讨论的话题:

什么是Java中的静态初始化块?

在Java中,静态关键字主要用于管理内存。静态关键字可以用于变量、方法、块和嵌套类。

现在让我们看一下定义静态块之前的代码:

public class Main{

 public static void main(String[] args){
   System.out.println("Hello World");
 }
}

输出

Hello World

我们都对它很熟悉。现在的问题是。

我们可以在没有main方法的情况下打印Hello World吗?

答案是肯定的

现在让我们看看静态初始化块的定义。
程序中的静态块是一组由JVM(Java虚拟机)在main方法之前执行的语句。Java并不关心这个块是写在main( )方法之后还是在main( )方法之前,不管怎样,它都会在main方法之前执行:

public class Sample
{
    static{
        System.out.println("Hello World");
        System.exit(0);
    }
}

注意

这段代码只在1.6以下的java版本上工作。新版本的java
已经不支持这个功能了。我们必须在我们的类中加入静态块的main方法。

我们怎样才能创建一个静态初始化块呢?

public class Main 
{  
    static double percentage;  
    static int rank;  
    
    // Static Initialization Block
    static  
    {  
        percentage = 44.6;  
        rank = 12;  
        System.out.println("STATIC BLOCK");  
    }  
    public static void main(String args[])  
    {  
        Main st = new Main();  
        System.out.println("MAIN METHOD");  
        System.out.println("RANK: " + rank);  
    }
}

输出

STATIC BLOCK
MAIN METHOD
RANK: 12

属性

  • 静态块在类被加载到内存中时自动执行。
  • 我们可以在一个类中制作多个静态初始化块。静态块按照它们被声明的顺序连续执行,前两个静态块分配的值被最后一个(第三个静态块)所取代。
public class Main{

  static{
    System.out.println("I am in first static block.");
  }
  
  public static void main(String[] args){
     System.out.println("Hello World.");
  }
  
  static{
   System.out.println("I am in second static block.");
  }
}

输出

I am in first static block.
I am in second static block.
Hello World.
  • 在整个程序中,静态初始化块将只执行一次
  • 这个块将不会返回任何东西
  • 被检查的异常不能被抛出

使用方法

  • 静态初始化块在类加载时执行,因此在类加载时,如果我们想执行任何活动,我们必须在静态块中定义。
  • 静态块被用来加载本地方法。
  • 静态块用于初始化静态成员。

真实世界的实现

问题陈述

你得到了一个带有主方法的类解决方案。完成给定的代码,使其输出一个平行四边形的宽和高的面积。你应该从标准输入中读取变量。

如果H<=0或B<=0,输出应该是 "java.lang.Exception:宽度和高度必须是正数",不带引号。

输入:
平行四边形的宽度和高度。

输出:
面积,如果B和H都大于0,
则打印异常,否则: 约束条件:
-100<=B,H<=100

解释

很简单的问题,在这里我们将接受输入,检查它们,并在需要时打印异常。但有趣的是,我们将在静态块的帮助下接受输入或打印异常。让我们开始吧:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

// Step 1: Create the Solution class
public class Solution {

  // Step 2: Create the required instance variable(must be static)
  static int B,H;
  static boolean flag = true; 
  
  /* Step 3: Initialize those variable (take user input) with the help of static block*/
  
  static{
  
      Scanner sc= new Scanner(System.in);
      B= sc.nextInt();
      H= sc.nextInt();
     
     try{
            if(B<=0 || H<=0){
                
            /* Step 4: make the flag false and throw the exception with the specific message */
                flag= false;
                throw new Exception("Breadth and height must be positive");
            }
      }
     catch(Exception e){
     
          // Step 5: catch the exception and print it.
          System.out.println(e);
     }
  }

public static void main(String[] args){

      // Step 6: give the logic for finding the area
		if(flag){
			int area=B*H;
			System.out.print(area);
		}
		
	}//end of main

}//end of class

在你的编辑器中试试吧。

通过OpenGenus的这篇文章,你一定对Java中的静态初始化块有了完整的了解。