Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
232 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...