-2

I've got a xxx.java file and it has a package level class of:

class Foo<T> {
    public static int classVar = 1;
}

No problem, compiles, but if I wrap it into another class:

class Outer {
    class Foo<T> {
        public static int classVar = 2;
    }
}

Then it doesn't compile, saying that the static declaration of inner class Outer.foo is invalid, and static is only allowed in declaration of constant variable.

This syntax rule looks confuse to me----let's see from the Java language perspective, what would happen if static is allowed to be used like my program does? Will it lead to any ambiguous program? Or any Runtime problem?

Thanks for explanations!

oguz ismail
  • 1
  • 16
  • 47
  • 69
Troskyvs
  • 7,537
  • 7
  • 47
  • 115

1 Answers1

1

Yes, this is right.

class Foo is not static, but dependent of instances of Outer.

That's the reason you could not statically access classVar, so this is not allowed because it would not make sense in any case.

What you could do instead is to make Foo static:

class Outer {
    static class Foo<T> {
        public static int classVar = 2;
    }
}

This way, one could statically access classVar like so: Outer.Foo.classVar.

JayC667
  • 2,418
  • 2
  • 17
  • 31