[英]Is there a way for anonymous inner classes in Java to “lose” their scope?
[英]Java Scope and Lifetime (inner classes)
我需要解釋為什么以下代碼將無法編譯(就范圍和生存期而言):
class ClassInMethod
{
public static void main(String[] args)
{
int local = 1;
class Inner
{
public void method()
{
System.out.println(local);
}
}
}
}
我認為這是因為:任何在內部類中使用但未聲明的局部變量都必須聲明為“ final”。 因此,在此示例中,“ local”必須聲明為final,因為它的范圍和生存期在main方法內(因此需要更改為:final int local = 1;)。
還有其他建議嗎?
請參閱http://techtracer.com/2008/04/14/mystery-of-accessibility-in-local-inner-classes/了解有關編譯器如何使用final
技巧來解決內部類問題的說明(例如,作用域和一生的問題)。
只是嘗試編譯它。 編譯器輸出:
ClassInMethod.java:11: local variable local is accessed from within inner class; needs to be declared final System.out.println(local); ^ 1 error
您必須使局部變量成為final
變量的原因是Java將其值復制到內部類的實例中。 幕后發生的事情是,編譯器生成(大致)與此對應的字節碼:
class ClassInMethod {
public static void main(String[] args) {
int local = 1;
// this happens when you do: new Inner()
ClassInMethod_main_Inner inner = new ClassInMethod_main_Inner();
inner.local = local;
}
}
// the inner class
class ClassInMethod_main_Inner {
int local;
public void method() {
System.out.println(local);
}
}
如果local
沒有final
,你可以改變它的當值之間Inner
被實例化,並在method()
被調用,調用method()
會使用的舊值local
。 這可能是不正確的行為。 要求final
的原因是為了使內部類的行為更直觀。
(有些語言沒有此限制,但是它需要編譯器和運行時的顯式支持。到目前為止,Java的開發人員尚未決定致力於實現它。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.