Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local class can access non-final variable in java 8

Before Java 8, We were not able to use non-final variables inside local class. But now they are allowing final as well as effectively final(who's values has not been changed), can be referred by local classes. What i know(Correct me if i am wrong), they didn't supported referring non-final values because there values can be changed. So, how they are supporting it now and why it was not supported earlier.

like image 321
Ashok Avatar asked May 10 '14 12:05

Ashok


People also ask

Can a local class have access to non final local variables?

Accessing Members of an Enclosing Class In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final.

Can local inner class access non final local variables Mcq?

A local class can only access local variables that are declared final in java.

Can local variables be accessed outside the class?

Variables defined in the class are available to all non-static methods declared in the class, called fields or class members. Their access modifier does not affect their scope within the class, and they can be accessed outside of the class using access modifiers.

Can local variable is final?

Most importantly, We can use local variable as final in an anonymous inner class, we have to declare the local variable of anonymous inner class as final.


1 Answers

The situation has not changed at all, actually. The compiler is just a bit smarter, and doesn't force you to use the final keyword anymore.

If it detects that the variable is effectively final, i.e. assigned only once, and never after, everything is good. If it detects that it's not effectively final, it refuses to compile.

So, instead of forcing you to make a variable final, it detects it automatically. But you still can't use non-effectively-final variables inside an inner class or lambda.

like image 195
JB Nizet Avatar answered Oct 17 '22 21:10

JB Nizet