This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Accessing outer class members in a static nested class. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing outer class members in a static nested class." Watch "Accessing outer class members in a static nested class." New topic
Author

Accessing outer class members in a static nested class.

shantanu kaushik
Greenhorn

Joined: Dec 12, 2011
Posts: 6
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
Sheriff

Joined: Sep 28, 2004
Posts: 18914
    
  40

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

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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.
 
 
subject: Accessing outer class members in a static nested class.