java - 为什么我在 Java 的 main() 中再次声明静态字段可以成功?

标签 java static field

我声明了一个private static double fd,然后我在 main() 中再次声明了double fd。为什么我可以编译运行成功?

    public class HelloWorld {
    private static double fd = 1.0;

    public static void main(String[] args){
        System.out.println(fd); //1.0
        double fd = 2.0;
        System.out.println(fd); //2.0


    }
}

最佳答案

来自 JLS Scope of a Declaration部分:

The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is not shadowed.

来自 JLS Shadowing部分:

Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.

这意味着您不能使用简单名称 (df) 来引用类级别 df 变量,因为它被本地 df 变量遮蔽。但仍然有两个变量,您可以使用带有类名的静态变量:

public static void main(String[] args){
    System.out.println(fd); //1.0

    double fd = 2.0;

    System.out.println(fd); //2.0
    System.out.println(HelloWorld.fd);
}

关于java - 为什么我在 Java 的 main() 中再次声明静态字段可以成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55606145/

相关文章:

PHP - 序列化一个具有静态属性的类

python - Odoo - 添加自定义字段属性?

python - 动态添加字段到数据类对象

java - 如何在 Java 中以 sudo 权限执行 bash 命令?

java - 不同的层次结构

java - Intellij 没有显示任何语法错误/没有给出任何建议

c# - smallint转int的datarow字段扩展方法

java - 如何使用java泛型删除重复代码

java - 无法获取静态字段的值

java - 是否可以在不扩展它的类方法中引用抽象类方法?