java - Why can't I declare and initialize static variable in inner class? -


this question has answer here:

class outer class. class b inner class of a, , class c inner class of b.

all 3 classes declare , initialize 1 static final variable.

this object in class a:

static final object x = new object(); 

class b:

static final object x1 = new object(); 

class c:

static final object x2 = new object(); 

the problem variable in class compiles fine, in b , c variable not.

error message:

the field can not declare static; static field declared in static , top level type

the string, , int in class b , c doesn't receive error.

complete code:

class {   static final object x = new object();   static final string s = "s1";   static final int y = 1;    class b {     static final object x1 = new object();     static final string s1 = "s1";     static final int y1 = 1;       class c {       static final object x2 = new object();       static final string s2 = "s1";       static final int y2 = 1;      }   } } 

you can't have static fields/method in regular inner classes, because, inner classes work instance of outer classes.

so, static can't there instances.

but can have compile time constants, check jls 8.1.3. x, x1, x2 not compile time constants, while s1, s2, y1, y2 compile time constants

inner classes may not declare static initializers (§8.7) or member interfaces, or compile-time error occurs.

inner classes may not declare static members, unless constant variables (§4.12.4), or compile-time error occurs.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -