有效地最终-内部类访问 [英] Effectively final - Inner classes access

查看:63
本文介绍了有效地最终-内部类访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内部类只能访问final或有效的final变量.我不明白,为什么无论如何都可以访问实例变量,但是局部变量和方法参数至少需要有效地最终确定?

Inner classes only have access to final or effectively final variables. I don't understand though, why an instance variable can be accessed no matter what, but local variables and method parameters need to be at minimum effectively final?

考虑以下代码:

public class BookStore {   

    private static final int taxId = 300000;   
    public String name;   

    public String searchBook(final String criteria) {      
        int count = 0;      
        int sum = 0;      
//      name = "";      I can uncomment this -> no compile error
        class Enumerator {         
            String interate(int k) {    
                System.out.println(name);
                System.out.println(sum);
                return "";         
            }             
        }            
//      sum++;      If I uncomment this, a compile error will be thrown.
        return "";
    }

}

为什么局部变量+方法参数必须有效地成为最终变量?

Why is it necessary that local variables + method arguments need to be effectively final?

推荐答案

这是因为局部变量的范围所致.它们的范围是声明它们的方法.一旦执行离开该方法,它们将不再有效.但是,内部类(例如您的Enumerator类)可以在方法执行之后继续存在,例如通过返回对类实例的引用.

It's because of the scope of the local variables. Their scope is the method in which they are declared. Once execution has left the method, they are no longer valid. However, an inner class such as your Enumerator class can live on past the method execution, e.g. by returning a reference to a class instance.

因此,可以在声明该类的方法之外访问Enumerator类及其方法.在这一点上,它需要假定它引用的局部变量具有与在实例化该类时执行的值相同的值.

Thus, the Enumerator class and its methods can be accessed outside of the method in which it is declared. At that point, it needs to assume that the local variables it referenced have the same value they had when execution instantiated the class.

对于实例变量,这些变量和内部类的作用域相同-只要存在父类实例,它们都可用.

For instance variables, the scope of these and of the inner class is the same - they are both available as long as the parent class instance exists.

这篇关于有效地最终-内部类访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆