Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner class doubt

 
raja kanak
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The above code shows error at //1 while compiling. I thought since a is declared as final, it can be used inside MethodLocalClass. But what went wrong?
 
Jesse Custer
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are reassigning a final variable. You cannot give 'a' a new value.
 
raja kanak
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jesse Custer:
You are reassigning a final variable. You cannot give 'a' a new value.


I changed //1 as
System.out.println(a);

Still it is problem, "Identifier expected".
 
ShivKumar Rajawat
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Live,
After this replacement your inner class structure becomes :

class MethodLocalClass {
System.out.println(a);
}
instead of puuting this statement directly inside the class , could you please try creating a member method and then put this statem,ent in that method.
 
raja kanak
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks ShivKumar for your reply. As per your suggestion I modified my code as at //0 final int a; and at //1 included a=5 which gives compile time error "Cannot assign a value to final variable". So i commented //1 and again it complains that "variable a might not have been intialized".

That means we must initialize the variable a before the MethodLocalClass definition.

Again at //0 i removed final modifier, then the compiler error is "local variable a is accessed from within inner class; needs to be declared final"

Conclusion: To access a local variable inside inner class, that variable should be declared final as well as it should be initialized outside the inner class.

Please correct me, if I am wrong.

raja
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JSL.....

A blank final (�4.12.4) field of a lexically enclosing class may
not be assigned within an inner class.


and ...

Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.


Switch statements can be fun in what they do an don't allow with finals too.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic