Java静态字段使用

标签 java static

我申请了一份工作,他们给了我一个 Java 测试。有许多我不熟悉的未知概念,也有较新的概念。一个是关于静态字段。我在下面发布了一个最奇怪的问题并寻求帮助。

代码在注释中包含问题。

public class MyClass {

    //what is the purpose of section, I mean for which purpose is it being used?
    //can variables inside of belove section be used or not. If can be used, then how?
    static{ 
        int a=5;
        double x=4.1;
    }

    //why this does not give any error because of redecleration of integer a?
    static int a=4;

    public static void main(String[] args) {
        System.out.println(a+"");//the output is 4
    }

}

最佳答案

这个 block

static{ 
    int a=5;
    double x=4.1;
}

被称为静态初始化器。当可能需要多个语句来初始化一个字段时,它用于初始化 static 字段。

但在这里,您实际上并没有初始化任何静态变量。您刚刚声明了两个局部变量。

这是重要的行:

static int a=4;

关于Java静态字段使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20200783/

相关文章:

java - 对象内部的静态对象引用被复制吗?

ios - 无法使用sharedStore传递带有内容的数组?

c# - 麻烦声明静态枚举,C#

java - 有 ReSTLet TaskService 的示例吗?

java - Spring Boot Maven 插件 : Exclude properties file from final jar

java - Java 中的 SQL 命令错误

oop - 类只有静态字段和方法是不好的做法吗?

java - 如何只打印某些字母

java - 使用 Apache Commons-Imaging/Sanselan 更新 Tiff-Metadata

c++ - 向静态控件发送文本