2017-05-08 30 views
-2

我已经从SoloLearn学习Java中final变量的声明,并在整个下面的代码都有所涉猎:的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前主声明方法?

当最终PI 在主方法中声明时,代码给出了一个错误:表达式的非法开始,它期望在单词static和final之间有分号。为什么不能在主要方法中使用最终变量PI?

+0

你问谷歌吗? –

+3

在开始在SO上发布问题之前,我建议继续阅读您的教程。初学者的问题没有问题(前提是他们以前没有被问及答案),但是在你能够提出符合SO格式的可靠问题之前,你仍然需要建立广泛的概念理解。 –

+3

没有冒犯,但我建议继续工作在您的基本Java技能。这是关于变量范围(本地,类)的极端基本的东西。短小回答:如果声明为局部变量,它**可以是最终的。但是局部变量当然不能是静态的和/或公共的。 –

回答

1

Why is the final variable PI declared before the main method?

因为代码的作者希望PI成为类的静态成员,而不是一个局部变量。

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

1

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

是的,因为静态字段属于类,而不是方法。方法只有局部变量。

阅读Java OO tutorial