Question
Why does InstantiationException occur in Java when accessing final local variables?
class Outer {
void method() {
final String finalVar = "Hello";
class Inner {
void display() {
System.out.println(finalVar);
}
}
Inner inner = new Inner();
inner.display();
}
}
Answer
InstantiationException in Java typically occurs when trying to access a non-instantiable class or a class whose instantiation is not permitted. When working with local classes or anonymous inner classes, accessing final local variables could lead to this exception if certain conditions are not met.
class Outer {
void method() {
final String finalVar = "Hello"; // Proper initialization
class Inner {
void display() {
System.out.println(finalVar); // Accessing final variable
}
}
Inner inner = new Inner();
inner.display();
}
}
Causes
- The final local variable may not be properly initialized before accessed.
- The enclosing method has completed execution, making the local variable unavailable.
Solutions
- Ensure that final local variables are initialized and remain in scope before the inner class accesses them.
- If the final variable is being accessed after the containing method has finished executing, consider using instance variables instead.
Common Mistakes
Mistake: Initializing final variable with a null value, but trying to access it before it's assigned.
Solution: Always assign a valid value directly to final variables prior to usage.
Mistake: Using the final variable outside the scope where it was declared.
Solution: Keep the final variable usage within its declaring method or scope.
Helpers
- InstantiationException in Java
- final local variables Java
- Java inner class exception
- Java final variable scope
- Java local variable access issues