Wednesday, August 19, 2015

"Variable is accessed within inner class. Needs to be declared final."

Problem:

"Variable is accessed within inner class. Needs to be declared final." or a similar error occurs.

Solution:

Declare the variable final, or make it an instance variable.

Explanation:

Java doesn't want developers to change local variables from within an inner class or an anonymous inner class.

Inner Classes and Local Variables

Any variable defined in a method and accessed by an anonymous inner class must be final. Or, as Oracle says:
"An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final"
Note: "effectively final" is something new introduced in Java SE 8. It is defined as a variable or parameter that is not declared as final, whose value is never changed after it is initialized.

But why make it so inner classes can't modify variables belonging to their outer scope?
The reason is that the inner class "captures" the variable. To understand why this matters, we need to understand the implications of how captured variables work. If you are familiar with closures, that is exactly what's going on here.
The inner class is a closure. It copies the variable from it's enclosing scope to a new variable, and brings just that copy inside the inner class. Anything it does to that copy is independent from the variable in the enclosing scope. So if the variable changes in the inner class, and then it is used later in the enclosing scope, the changes made in the inner class did not persist in the enclosing scope.

Basically, what happens in the inner class stays in the inner class.
Below is a proper scenario.

 
public class RadiusStuff { //This is the outer class
    public void start(Stage stage) { //This method is the enclosing context
    Button submit = new Button("Submit");
    final string radius = "10";
    submit.setOnAction(new EventHandler<ActionEvent>() {
        //This is the inner class, specifically an anonymous class.
        @Override
        public void handle(ActionEvent e) {
            submit.setText(radius);
        }
    });
  }
}

This functionality is by design.

Java wants the developer to use the final keyword on any variables that are going to be modified in the inner class. This prevents us from thinking the things we change in the inner class will persist in the enclosing scope.
In a way, adding the final keyword does not change the behavior of the code. Think about it. With or without the final keyword, any changes to the variable in the inner class won't persist, so why make any changes at all? Java forces developers to use final in this scenario just to emphasize that we shouldn't be modifying a local variable in an inner class.

But what if, in the closure, we are only reading from the variable and not writing to it? Does it still need to be declared final?
If you are using Java 7 or below, the answer is "yes".
In Java 8, if we are only accessing but not changing the variable, the variable is "effectively final" and does not need to be declared final.

The problem with this is that if we ever want to change the variable we won't be able to. In the below code I show an example of this case by assigning a new value to our "radius" variable, but it will not work.
 
public class RadiusStuff { //This is the outer class
    public void start(Stage stage) { //This method is the enclosing context
    Button submit = new Button("Submit");
    final string radius = "10";
    submit.setOnAction(new EventHandler<ActionEvent>() {
        //This is the inner class, specifically an anonymous class.
        @Override
        public void handle(ActionEvent e) {
            submit.setText(radius);
        }
    });
    radius = "15"; //This will throw compile-time error.
  }
}

Instance Variables

I mentioned under the "Solution" section that we could also just make the variable an instance variable. Does this really work? Why?
Referring back to Oracle's documentation we see that our inner class "cannot access local variables in its enclosing scope that are not declared as final..."
So why would an instance variable be an exception? Note the words "local variable". This only applies to variables declared within the method that the inner class is in, also known as the "enclosing scope".
So does this mean an anonymous inner class can change an instance variable, and have those changes persist outside of the inner class?
Yes.

 
public class RadiusStuff { //This is the outer class
    string radius = "10"; //Instance variable, no need to be final.

    public void start(Stage stage) { //This method is the enclosing context
    Button submit = new Button("Submit");
    
    submit.setOnAction(new EventHandler<ActionEvent>() {
        //This is the inner class, specifically an anonymous class.
        @Override
        public void handle(ActionEvent e) {
            submit.setText(radius);
        }
    });
    string radius = "15"; //This is allowed now.
  }
}

Other notes:

  • Variables defined in interfaces are implicitly final, even if they don't have the final keyword.
  • For variables that reference objects, the properties of the object can be modified, even if the variable is final. However, you cannot change which object the variable refers to.
  • You can find excellent information on closures here: C# in depth
  • The behavior mentioned in my post is similar between Java and C#, but there are some differences, so be careful. Perhaps I'll discuss those in a future post.

23 comments:

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. This comment has also been removed by the author. Nice!

      Delete
  2. Hi Brendon, Thanks for your clear explanation on why we need not to declare the local variable final implicitly on Java 8. I was confused, because the code compiled even though I did not use the final keyword.

    ReplyDelete
    Replies
    1. I'm glad it helped! Thanks for letting me know.

      Delete
    2. Me too.Although I don't modify the local variable,the code compiled failed.Did you have solve this problem? If so ,I hope you can explain for me

      Delete
  3. Thanks for this, solved a problem I was having. Instance variable really helped in this case.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. Hi i am creating an application and in this application i am fetching data from API and show it. for fetching data i am creating ServerRequestHandler class and main class. in ServerRequestHandler class i have a problem with veriable and getting this error "Variable is accessed within inner class. Needs to be declared final".
    this is my code.
    public void CoordinatesMethod(double Latitude, double Longitude,double Altitude){
    final String url = "http://"+ipAddress+"8298/api/GPSTrack/?latitude="+Latitude+"&longitude="+Longitude+"&altitude="+Altitude+"&DeviceName=Ismail";
    //String url = "http://\"+ipAddress+\"8298/api/GPSTrack/?latitude=\"+latitude+\"&longitude=\"+longitude+\"&altitude=74.3587&DeviceName=Ismail";

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener(){

    @Override
    public void onResponse(JSONObject response) {

    JSONObject jsonObject = response;
    boolean coordinates;
    JSONArray tableJsonArray;
    try {
    boolean isStatus;
    isStatus = jsonObject.getBoolean("Status");
    if (isStatus) {
    final Latitude = jsonObject.getDouble("Latitude".toString());
    final Longitude = jsonObject.getDouble("Latitude".toString());
    final Altitude = jsonObject.getDouble("Latitude".toString());
    } else {
    Toast.makeText(mCtx, "Try Again", Toast.LENGTH_LONG).show();
    }
    } catch (JSONException ex) {
    ex.printStackTrace();
    }
    }
    },
    please guide me about this problem thanks in advance

    ReplyDelete
    Replies
    1. Having Problem in these lines. i am adding final before variable.
      final Latitude = jsonObject.getDouble("Latitude".toString());
      final Longitude = jsonObject.getDouble("Latitude".toString());
      final Altitude = jsonObject.getDouble("Latitude".toString());

      Delete
  6. This comment has been removed by a blog administrator.

    ReplyDelete
  7. Thanks for your explanation, Bredan~ It links the Closure notion clearly to Inner Class. But would you talk more about WHY instance or class fields are mutable to Inner Class. Now I know Oracle says it can be done, but why? Does it means that instance fields are not captured by Inner Class? Does it related to stack and heap storage?

    ReplyDelete
  8. Finally someone who explained it clearly!

    ReplyDelete

Note: Only a member of this blog may post a comment.