Inner class and local variables

后端 未结 6 552
无人共我
无人共我 2020-11-30 12:48

Why do I need to declare a local variable as final if my Inner class defined within the method needs to use it ?

Example :

6条回答
  •  时光取名叫无心
    2020-11-30 12:57

    I think this is to prevent that the programmer would make mistakes. This way, the compiler reminds the programmer that the variable will not be accessible anymore when you leave that method. This is critical with looping. Imagine this code:

    public void doStuff()
    {
        InnerClass cls[] = new InnerClass[100];
        for (int i = 0; i < 100; ++i)
        {
            cls[i] = new InnerClass()
            {
                void doIt()
                {
                    System.out.println(i);
                }
            };
        }
    }
    

    When the doIt() method is called, what will be printed? i changed while looping. To prevent that confusion, you have to copy the variable to a local variable or create the variable final, but then you will be unable to loop.

提交回复
热议问题