Unable to declare static variable inside of static method

后端 未结 6 2013
误落风尘
误落风尘 2020-12-14 03:03
class Foo {
    public Foo() { }
}

class Bar {
    static Foo foo = new Foo(); // This is legal...

    public static void main(String[] args) { 
        static int         


        
6条回答
  •  无人及你
    2020-12-14 03:55

    You have to make the static final static or remove 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'.

    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.

    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;
    }
    

    However you could do this instead,

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

    It is better engineering at the expense of some ugliness.

提交回复
热议问题