I am new to Java and have been doing some basic coding since few days. Today while dealing with variables and inner class, I got stuck while using the non-final variable in innerclass.
I am using testNG framework for my work, so here is the scenario that I am trying,
=========
public class Dummy extends TestNG {
@Override
public void setUp() throws Exception {
log.error("Setup Goes here");
}
@Override
public void test() throws Exception {
String someString = null;
try {
someString = "This is some string";
} catch (Exception e) {
log.error(e.getMessage());
}
Thread executeCommand = new Thread(new Runnable() {
@Override
public void run() {
try {
runComeCommand(someString, false); <=====ERROR LINE
} catch (Exception e) {
log.error(e.getMessage());
}
}
});
}
@Override
public void cleanUp() throws Exception {
}
}
==========
When I wrote the above code, it thrown an error saying "can not refer to non-final variable in inner class". So I implemented one of the suggestion provided by eclips i.e declare someString variable in the parent class. Now the code looks like this,
==========
public class Dummy extends TestNG {
String someString = null; <=====Moved this variable from test() to here
@Override
public void setUp() throws Exception {
log.error("Setup Goes here");
}
@Override
public void test() throws Exception {
<same code goes here>
}
@Override
public void cleanUp() throws Exception {
}
}
==========
Now it does not show any error in eclips. I wanna know, Why its now accepting the variable in inner class even though its not final. Shouldn't it fail with the same error? Will this work now? Any help will be great.