• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing outer class members in a static nested class.

 
shantanu kaushik
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can I access members of enclosing non-static class in a static nested class as non static member cannot be accessed in a static block
 
Henry Wong
author
Marshal
Pie
Posts: 21420
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shantanu kaushik wrote:How can I access members of enclosing non-static class in a static nested class as non static member cannot be accessed in a static block



First, do you know why a static block can't access a non-static field? This reason is not arbitrary. The Java designers didn't just do it for style. An instance is not needed to make the static method call, so how can you get something that may not even exist?

Second, do you know that static inner classes, aka nested classes, do not need an instance of an outer class to be created? In fact, you will get a compilation error. Instances of static inner classes do not have an enclosing outer class, and hence, don't have any fields of the outer class.


So.... you want to access something that does not exist, from an instance that may or may not have been used to call a method?


If you want to do this, I recommend passing an instance of the outer class as a parameter to the static method.

Henry
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
If you want to do this, I recommend passing an instance of the outer class as a parameter to the static method.



Or make the nested class non-static. Without knowing more about your design and requirements, it's impossible to say which is the more appropriate approach here.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic