user2176737
user2176737

Reputation: 789

Static fields in inner classes

If I have class structure like that

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 static field in class Bar acts? I mean, it is the same instance for all Foo objects or for each instance there is different static field?

Upvotes: 5

Views: 284

Answers (3)

Boris the Spider
Boris the Spider

Reputation: 61128

The code will not compile, the compiler will emit

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

You need to have a static inner class in order for this code to compile.

Upvotes: 1

Fuv
Fuv

Reputation: 922

Your question is not correct. Just it makes no sense of asking about something that doesn't exist. The only possibility in that situation is to make inner class static. Then for each instance of outer class you have one static instance of inner class. And as a result one static variable of this inner class.

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

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

Upvotes: 4

Related Questions