What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
Kick the error "No enclosing instance of type Foo is accessible" to the curb by first guaranteeing an existing instance of the outer class Foo
when kickstarting its inner class. But here's a shortcut: if the inner class couldn't care less about outer instance variables, just sweep it under the static
rug.
Getting a firm grip on inner classes (and their static counterparts)
Inner classes, Java's slight of hand to keep code tight and neat. To be a master magician, understanding them is your first trick.
static
vs non-static
inner classes
A non-static inner class is like your kid brother, needs you around to run wild. However, a static nested class is like your cool cousin, doesn't need you to have a good time.
What's mine is yours, and what's yours is mine?
Inner classes can sneak into any corner of the outer class, doesn't matter if it's private or not. But the outer class can't return the favor unless the static nested class and its assets are in the public domain or at least within the same package.
When to call what
Use an inner class when it needs to have the outer class around, and a static nested class when it's fine flying solo. Static nested classes are often found masquerading as builders, iterators, or as cohorts in a top-level class.
What to do with these local lads
Local inner classes are those buddies who only show up at specific parties (or blocks). They can't be declared static but have access to the snacks (local final variables) at the party (block).
Creating clean and crisp code
The one-job policy
One class, one responsibility. If an inner class starts doing the job of two, it's time for it to move out and become a top-level class.
Nested is nice, but not too deep
Deeply nested is the stuff nightmares are made of, can make your code unreadable. If a nested class starts getting a little too complex, it might be time to upgrade it to a top-level class.
Be a generous refactoring god
Turning a non-static inner class into a static nested class often axing that annoying "No enclosing instance" error. Plus, it also lightens the memory load, as static nested classes don't hold on to the outer class instance.
Designing for the future, because it arrives anyway
If a class could talk about the future, it might help decide whether to use static or non-static inner classes. Think ahead, plan better.
Was this article helpful?