1

I know,this question has been asked already and I an advance apology for asking it again but I am not able to figure out the exact reason why this is so?Can someone please help me out with it? For e.g.-

public class File
{
    public static void main(String[] main)
    {
        File obj=new File();
        obj.method();
    }
    void method()
    {
        for(int i=0;i<10;i++)
        {
            class Inner
            {
                void display()
                {
                    System.out.println("i is : "+i);  //Gives error,i needs to be declared final
                }
            }
            Inner cls=new Inner();
            cls.display();
        }
    }
}

My questions are-

  • Why the variable i needs to be declared final if I want to use it in display() method of Inner class?
  • If I want to display i inside the display method in each iteration,then how may I do so?Because if I declare i to be final with initial value 0,then I will not be able to iterate over it.

Thanks .....

Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42
  • If you know that the question you're asking is duplicate, you have to explain **why the duplicate doesn't address your concerns in the question itself.** – durron597 Aug 30 '15 at 03:37

1 Answers1

1

1)That variable needs to be final or effective final because of security reasons. What if the object using in that modifying the passed object??

2) You have to just move your for loop inside the class. No other way around.

An inner class just want to use the the instance members, just use them, that is the only thing you can do inside inner class. You have no command over that. To achieve that functionality, Java made the rule of final or effective final.

Ok, let see what happens when you made the variable final ?

All the copies of those final variables will be used by the inner class not the actual varibles.

If you not heard of the term effectively final here you go : Difference between final and effectively final

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307