如何在 Main 方法中声明静态变量?
我们可以在 Main
方法中声明 Static
变量吗?因为我收到一条错误消息:
Illegal Start of Expression
Can we declare Static
Variables inside Main
method? Because I am getting an error message:
Illegal Start of Expression
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
显然,不,我们不能。
在Java中,
static
意味着它是一个类的变量/方法,它属于整个类,但不属于其某些对象之一。这意味着
static
关键字只能在“类范围”中使用,即它在方法内部没有任何意义。Obviously, no, we can't.
In Java,
static
means that it's a variable/method of a class, it belongs to the whole class but not to one of its certain objects.This means that
static
keyword can be used only in a 'class scope' i.e. it doesn't have any sense inside methods.您可以在
main
方法(或任何其他方法)中使用静态变量,但您需要在类中声明它们:这完全没问题:
这也很好,但在这种情况下,
someNumber
是一个局部变量,而不是静态变量。You can use static variables inside your
main
method (or any other method), but you need to declare them in the class:This is totally fine:
This is fine too, but in this case,
someNumber
is a local variable, not a static one.因为静态变量是在类加载时分配内存的,并且只分配一次内存。现在,如果方法内有一个静态变量,那么该变量属于该方法的作用域,而不是类的作用域,JVM无法为其分配内存,因为方法是在类对象的帮助下调用的,并且是在运行时而不是在类加载时调用。
Because the static variables are allocated memory at the class loading time,and the memory is allocated only once.Now if you have a static variable inside a method,then that variable comes under the method's scope,not class's scope,and JVM is unable to allocate memory to it,because a method is called by the help of class's object,and that is at runtime,not at class loading time.
由于静态变量可用于整个类,因此从概念上讲,它只能在作用域为全局的类之后声明,而静态块或方法都有自己的作用域。
As static variables are available for the entire class so conceptually it can only be declared after the class whose scope is global where as static block or methods all have their own scope.
你不能,你为什么要这么做?您始终可以在它所属的类级别上声明它。
You cannot, why would you want to do that? You can always declare it on the class level where it belongs.
在 C 中,您可以静态分配局部作用域变量。不幸的是,Java 并不直接支持这一点。但是您可以通过使用嵌套类来达到相同的效果。
例如,以下内容是允许的,但这是糟糕的工程,因为 x 的范围比它需要的大得多。两个成员(x 和 getNextValue)之间也存在不明显的依赖关系。
人们真的很想做以下事情,但这是不合法的:
但是你可以这样做,
这是更好的工程,但代价是一些丑陋。
In C, you can have statically allocated locally scoped variables. Unfortunately this is not directly supported in Java. But you can achieve the same effect by using nested classes.
For example, the following is allowed but it is bad engineering, because the scope of x is much larger than it needs to be. Also there is a non-obvious dependency between two members (x and getNextValue).
One would really like to do the following, but it is not legal:
However you could do this instead,
It is better engineering at the expense of some ugliness.