I was having a bizarre time trying to reference instance variables of a class within a runnable. Here was my (simplified) code:
public class Hello{
private Boolean truth;
public Hello(Boolean truthParam){
this.truth = true;
Runnable myRunnable = new Runnable(){
public void run(){
if (this.truth){
System.out.println("i declare the truth!");
}else{
System.out.println("come back tomorrow");
}
}
};
}
}
When I compiled this code, I got "error: cannot find symbol ... symbol: variable truth"
I thought perhaps within the context of the Runnable, "this" was no longer the main class object; however, I printed "this" to the console, and it was an instance of Hello. Which begs the question: why was I unable to access my instance variable via this?
I then removed the "this" from if (this.truth)
, converting it to if (truth)
; needless to say, this compiled and ran. I am quite confused by this behaviour I cannot explain. Perhaps I am simply misunderstanding the intricacies of "this"...