I was reading topic on Lambda Expression and I got to know that inner class or Lambda expressions don't have access to the variables outside of its scope except if they are declared as final
.
I wrote a simple code in which two variables are declared, one is declared inside of the method dosomething()
named i
and another outside of all the methods, a class field (Member variable) named k
.
When inner class is created I've noticed that the it have access to variable k
but not i
variable. Can I know the reason behind this?
Code :
interface JustAInterface
{
void printanything();
}
class OtherClass
{
//Declaring Variable Outside of All Methods
int k = 5;
void dosomething()
{
//Declaring Variable Inside the Method
int i = 10;
JustAInterface obj = new JustAInterface()
{
@Override
public void printanything()
{
i = 10;
k = 20;
}
};
}
}
public class AnotherRough
{
public static void main(String args[])
{
OtherClass otherObj = new OtherClass();
otherObj.dosomething();
}
}
The same question has been asked by me, head to the link which is given at the top to find the answers.