A reference within a method that is identical to one of its parameters reference refers to the parameter correct?

Viewed 47

Towards the end of this section in a oracle tutorial of lambda expressions it seems as if it is saying that x is referring to a member in the enclosing class of the method, but since the method has a parameter reference identical to x I think it refers to the local parameter and not a member of the enclosing class.

For example, the lambda expression directly accesses the parameter x of the method methodInFirstLevel. To access variables in the enclosing class, use the keyword this. In this example, this.x refers to the member variable FirstLevel.x.

But then the tutorial seems to immediately contradict itself:

However, like local and anonymous classes, a lambda expression can only access local variables and parameters of the enclosing block that are final or effectively final. For example, suppose that you add the following assignment statement immediately after the methodInFirstLevel definition statement:

void methodInFirstLevel(int x) {
    x = 99;
    // ...
}

Because of this assignment statement, the variable FirstLevel.x is not effectively final anymore.

What? The assignment in that example method is x = not this.x = so how does that assignment affect FirstLevel.x at all?

2 Answers

From what I gathered, the tutorial was saying that the x = 99 in the example lambda function was not accessing the class member variable. It was attempting to modify the function parameter, which must be final, therefore, it was an invalid operation. The x = 99 would have generated an error.

The tutorial later said that it affected the member variable, FirstLevel.x. This was incorrect, as x = 99 can only reference the function parameter. On the other hand, this.x would have referenced FirstLevel.x.

As a general thing what is passed to a function is a reference. Within the function a local variable is then assigned this reference. It does not generally cause any change to the variable outside the function unless you cause this with some form of global variable. The coincidence of names does not cause any issue because they point to different memory locations.

Related