• Post Reply Bookmark Topic Watch Topic
  • New Topic

why we cant have static fields in an inner class??  RSS feed

 
abhishek kunal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
someone may say that, as inner objects cannot exist without outer objects, so an inner object cannot exist independently. they are contained in some objects(outer objects). and as static variables cannot be there in an object, hence an inner class cannot have static variables?? if you agree with the logic made above then i have few points to discuss and if dnt agree then please tell your point ....
 
Jaydeep Vaishnav
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What points would you like to discuss?
 
abhishek kunal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
means you agree with the logic,ok...

now as static fields are initialized as soon as a class is loaded even before an object of that type is created(by class loader of jvm), now as it will load an outer class and do static initialization for that class, at the same time it could load the inner class as well, and initialize the static variables....so y to wait for any outer object's creation for the inner class object's static data ??(that was the reason for not having static fields in an inner class according to the logic made above..)?? so we jvm cd initialize the static member just after it initialized the outer static variables.......what say??? hope you getting me ...!! ..


if you would say that you access an inner class object with the help of only outer class object, so no sense of static variables..agreed but wat abt if i want to do something like this....

outer.inner.mystatic;//where mystatic is the static variable (Assuming if i wanted to do this)
 
Jaydeep Vaishnav
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static Nested Class could help you. These classes are nested but not strongly associated with outer class. While inner class is a member of outer class and hence we cannot have static fields in it.
 
Salil Vverma
Ranch Hand
Posts: 257
Hibernate Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is correct, you can have an static variable in an inner class provided inner class is also static. Have a look on the below code. It works fine and prints 200 on the console

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!