Java: 在哪里放置最终变量的声明
Java: Where to place declaration of final variable
我一直在从 SoloLearn 学习 Java 中的最终变量,并且偶然发现了以下代码:
class MyClass
{
public static final double PI = 3.14; //defines a constant double PI = 3.14
public static void main(String[ ] args)
{
System.out.println(PI); //prints 3.14
}
}
为什么最后一个变量PI声明在main方法之前?
在main方法中声明final PI 时,代码报错:表达式的非法开始,static和final之间需要分号。为什么final变量pi不能在main方法中?
Why is the final variable PI declared before the main method?
因为代码的作者希望 PI
成为 class 的静态成员,而不是局部变量。
When final PI is declared in the main method, the code gives an error: illegal start of expression, and it expects a semicolon between the words static and final.
您不能在局部变量的声明中使用 static
。您可以在 main
中只有 final double PI = 3.14;
,但它仅在 main
中是本地的。
Why is the final variable PI declared before the main method?
它可以定义在后面,但是在 Java
中字段通常放在构造函数和方法之前
When final PI is declared in the main method, the code gives an error
是的,因为静态字段属于 类,不属于方法。方法只有局部变量。
我一直在从 SoloLearn 学习 Java 中的最终变量,并且偶然发现了以下代码:
class MyClass
{
public static final double PI = 3.14; //defines a constant double PI = 3.14
public static void main(String[ ] args)
{
System.out.println(PI); //prints 3.14
}
}
为什么最后一个变量PI声明在main方法之前?
在main方法中声明final PI 时,代码报错:表达式的非法开始,static和final之间需要分号。为什么final变量pi不能在main方法中?
Why is the final variable PI declared before the main method?
因为代码的作者希望 PI
成为 class 的静态成员,而不是局部变量。
When final PI is declared in the main method, the code gives an error: illegal start of expression, and it expects a semicolon between the words static and final.
您不能在局部变量的声明中使用 static
。您可以在 main
中只有 final double PI = 3.14;
,但它仅在 main
中是本地的。
Why is the final variable PI declared before the main method?
它可以定义在后面,但是在 Java
中字段通常放在构造函数和方法之前When final PI is declared in the main method, the code gives an error
是的,因为静态字段属于 类,不属于方法。方法只有局部变量。