Static fields in inner classes

If I have a class structure like

public class Foo{
    //declaring fields and methods


    Foo(int k){
        Bar.a = k;
    }
    public class Bar{
        public final static int a;
    }
}

And if I create many instances of Foo, how does the static field in the Bar class work? I mean, is this the same instance for all Foo objects, or is there a different static field for each instance?

+5
source share
3 answers

I think that the Inner class cannot have static members, as this requires an instance of the Outer Class.

+4
source

The code will not compile, the compiler will publish

COMPILATION ERROR : 
-------------------------------------------------------------
... error: Illegal static declaration in inner class blah.Foo.Bar
1 error

To compile this code, you must have an inner class static.

+1
source

Your question is incorrect. It just doesn't make sense to ask about something that doesn't exist. The only possibility in this situation is to make an inner class static. Then for each instance of the outer class you have one static instance of the inner class. And as a result, one static variable of this inner class.

0
source

All Articles