无法在静态方法中声明静态变量

编程入门 行业动态 更新时间:2024-10-25 20:18:10
本文介绍了无法在静态方法中声明静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 class Foo { public Foo() { } } class Bar { static Foo foo = new Foo(); // This is legal... public static void main(String[] args) { static int a = 0; // ... But why this is not? } }

为什么我们不能在里面声明一个静态变量一个静态函数?

Why can't we declare a static variable inside of a static function?

推荐答案

你必须使静态最终静态或删除 static 。

在Java中,static表示它是类的变量/方法,它属于整个班级,但不是其中一个特定的对象。这意味着static关键字只能在类范围中使用。

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'.

通常,在C中,您可以静态分配本地范围的变量。不幸的是,这不是Java直接支持的。但是你可以通过使用嵌套类来实现相同的效果。

Generally, 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.

例如,允许使用以下内容,但这是一个糟糕的工程,因为x的范围远大于它需要是。此外,两个成员之间存在非明显的依赖关系(x和getNextValue)。

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).

static int x = 42; public static int getNextValue() { return ++x; }

人们真的想做以下事情,但这不合法:

One would really like to do the following, but it is not legal:

public static int getNextValue() { static int x = 42; // not legal :-( return ++x; }

但是你可以这样做,

public static class getNext { static int x = 42; public static int value() { return ++x; } }

以牺牲丑陋为代价更好的工程设计。

It is better engineering at the expense of some ugliness.

更多推荐

无法在静态方法中声明静态变量

本文发布于:2023-10-31 04:02:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544940.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   变量   声明   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!