简体   繁体   English

内部类和局部变量

[英]Inner class and local variables

Why do I need to declare a local variable as final if my Inner class defined within the method needs to use it ? 如果我在方法中定义的Inner class需要使用它,为什么我需要将local variable声明为final

Example : 示例:

class MyOuter2 {

private String x = "Outer2";

void doStuff() {
    final String y = "Hello World";

    final class MyInner {

        String z = y;

        public void seeOuter() {
            System.out.println("Outer x is "+x);
            System.out.println("Local variable is "+y);
            MyInner mi = new MyInner();
            mi.seeOuter();
        }
    }
}

} }

Why the String y needs to be a final constant ? 为什么String y需要是最终常量? How does it impact ? 它是如何影响的?

Local variables always live on the stack, the moment method is over all local variables are gone. 局部变量总是存在于堆栈中,当时方法已经超过所有局部变量都消失了。

But your inner class objects might be on heap even after the method is over (Say an instance variable holds on to the reference), so in that case it cannot access your local variables since they are gone, unless you mark them as final 但是即使在方法结束之后你的内部类对象也可能在堆上(假设一个实例变量保留在引用上),所以在这种情况下它不能访问你的局部变量,因为它们已经消失了,除非你把它们标记为final

The answer is the two are in different scopes. 答案是两者在不同的范围内。 So that variable could change before the inner class accesses it. 因此,在内部类访问它之前,该变量可能会发生变化。 Making it final prevents that. 使其成为最终阻止。

It's because the inner class inside a function actually makes a copy of the local variable because local variable may be destroyed after the function call while the instance of the local class still exists. 这是因为函数内部的类实际上是复制局部变量,因为在本地类的实例仍然存在的情况下,函数调用之后可能会销毁局部变量。 To make the two copies of the local variable always have the same value(to make them seem identical), you have to declare the variable as final. 要使局部变量的两个副本始终具有相同的值(使它们看起来相同),您必须将变量声明为final。

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? 当调用doIt()方法时,将打印什么? i changed while looping. i在循环时改变了。 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. 为了防止这种混淆,您必须将变量复制到局部变量或创建变量final,但是您将无法循环。

你的内部类是最终的,因此你不应该从最终实体内部修改任何内容。

According to Java memory model use of final variable guarantees that the final variable are always initialized. 根据Java内存模型,使用final变量可确保始终初始化最终变量。 We get error when we try to use local variable without initialization. 当我们尝试使用没有初始化的局部变量时,我们会收到错误 using final guarantees the inner class that local variable which is been used is initialized. using final保证内部类初始化已使用的局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM