Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Static fields in inner classes  RSS feed

 
shiran abbasi
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why can't i have static fields in inner classes?




After all of this i can access OuterClass.TimePrinter.i but i wondered why the java designers didn't allow the static field in inner classes?

Any help would be appreciated. Thanks in advance


[HENRY: fixed code tags]
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shiran abbasi wrote:Why can't i have static fields in inner classes?


First of all, static fields are allowed with static inner (aka nested) classes. Nested classes, as you probably know, don't require that instances of it, are owned by instances of its outer class.

shiran abbasi wrote:
After all of this i can access OuterClass.TimePrinter.i but i wondered why the java designers didn't allow the static field in inner classes?


Of course, this discussion is completely speculation, as there are currently no members of the Java design team on the ranch... but ...

If I had to take a guess, my guess would be that it would have been very weird to have a static field, that requires an instance of the outer class (or an instance of anything actually) to access.

Of course, you could counter argue that the compiler can make a special case for this, and basically treat static fields of the inner class as the same as static fields of the outer class.... which... then opens secondary questions such as... what benefit / purpose would this provide if it is the same as static fields of the outer class? what happens if a static field of the inner class has the same name of a static field of the outer class? what happens for the case of an inner class of another inner class? what happens if a static field of the inner class has the same name of a static field of a different inner class? .... or basically, how would you resolve the hiding rules for all these different cases? etc. etc. etc.

Henry
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!