Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

here is doubt about initializing final local var...

 
aditya makam
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,

This is the program.

interface I
{
void setval();
}
class Outer
{
String str;
public static void main(String arop[])
{
Outer out1= new Outer();
out1.method();
}
void method()
{
final String str1;
I obj = new I(){
public void setval()
{
str="aditya";
str1="makam";
}
};
obj.setval();
}
}


Its giving compile time error as shown below.Can anybody explain the reason?

waiting for your reply,

aditya makam
 
J Sato
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From: http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html

When an inner class refers to an instance variable that is a member of a lexically enclosing class, the variable of the corresponding lexically enclosing instance is used. A blank final (�4.5.4) field of a lexically enclosing class may not be assigned within an inner class.

If you move the declaration for str1 inside the setval() method, the code will compile.
[ April 06, 2006: Message edited by: J Sato ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use Code Tags to keep your code indentation intact.
 
Changchun Wang
Ranch Hand
Posts: 83
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
define a final variable in the method ,you must initlize it
java don't have is blank local final variable
so the final local variable is different from general local variable (not final variable )
the general variable can initlizew before using it;
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic