gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:01:20 26 4
gpt4 key购买 nike

我声明了一个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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com