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