Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variables in inner class not allowed why?

 
Chandra Bairi
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a non-static inner class, static final variables are allowed, but not static variables! why?
 
Joe Ess
Bartender
Posts: 9279
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static fields are associated with a class rather than a particular instance of that class. A non-static inner class is associated with a particular instance of the class that contains it. It doesn't make sense to have the member variable longer-lived than the class that declares it.
 
Steve Lovelace
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To be a bit more precise, static members are associated with a Class object. All classes loaded, even inner ones, will have exactly one Class object (ignoring multiple or badly-behaved classLoaders). So there is no logical reason for disallowing static members in inner classes. IMHO, the fact that they are not allowed leads to an unnecessarily complicated and foggy nested class specification.
And by the way, I hear the compiler is sneaking static members into inner classes as part of the assertion mechanism.
Chandra, you asked a good question.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic