If I have a simple class like this:
public class Example{
int y = 2;
String z = "textExample";
}
Why is it that inside a Listener I can change a member of a variable of that class but now the variable itself? Or for that matter even a primitive such as an int
.
Imagine this function in another class:
public class newClass {
protected void doActivate() {
ItemCreation model = new Itemcreation(); //A class with visible moving parts
Example ex = new Example();
int i = 2;
model.getSourceProperty().addListener((o, oldVal, newVal) -> {
//do stuff
ex.z = "sss"; //THIS I CAN DO and Works
Example exTmp = new Example();
ex = exTmp; //This complains with message: Local variable ex defined in an enclosing scope must be final or effectively final
i= 4;//This also complains with message: Local variable i defined in an enclosing scope must be final or effectively final
});
}
I looked online a lot and I didn't find any answer for this. All I found was that "Java language has a feature in which local variables accessed from within (anonymous) inner classes must be (effectively) final". But if that is the case, why can I change the members of the Example
class, which isn't final?