无法在静态方法中声明静态变量 [英] Unable to declare static variable inside of static method

查看:684
本文介绍了无法在静态方法中声明静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于无法在静态方法中声明静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆