0

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Eddy
  • 344
  • 5
  • 16
  • This question is [easily searched](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=why+restriction+local+variables+lambda+java+site:stackoverflow.com) – Hovercraft Full Of Eels Jun 11 '16 at 14:24
  • I searched but didn't saw that post that's the reason I made another question :) – Eddy Jun 11 '16 at 14:25

0 Answers0