Java Reference
In-Depth Information
Class-level B
CLASSA Value: Class-level B
METHODA Value: Method-level A
Hello
CLASSA Value: Class-level B
METHODA Value: Method-level A
Note The CLASSA variable is overridden by a variable using the same identifier
within the InnerClass class. Therefore, the CLASSA instance variable that belongs
to VariableAccessInner is not printed from within the lambda expression.
How It Works
Lambda expressions have access to the variables located within the enclosing class.
Thus, a lambda expression contained within a method of a class can access any in-
stance variables of the enclosing class. There is no additional scope added to a lambda
expression, so it can access fields, methods, and local variables of the enclosing scope.
In the solution, the lambda expression contained within the lambdaInMethod()
method can access all of the fields that are declared within either class. This is because
both the inner class and its outer class enclose the lambda. One thing to note is that if
an inner class contains an instance variable of the same name as a variable that has
been declared in the outer class, then the lambda will use the variable of its enclosing
class. Therefore, in the solution, the InnerClass CLASSA field is accessed from
within the lambda expression, rather than the outer class reference.
Local variables that are referenced from within a lambda expression must be either
final or effectively final. Therefore, if a lambda expression attempts to access a vari-
able that has been changed within the context of an enclosing method, an error will oc-
cur. For instance, suppose that the method in the solution were changed to the follow-
ing:
void lambdaInMethod(String passedIn) {
String METHODA = "Method-level A";
passedIn = "test";
Consumer<String> l1 = x -> {
System.out.println(x);
System.out.println("CLASSA Value: " + CLASSA);
Search WWH ::




Custom Search