[英]Java - Anonymous class are static or not
我知道這取決於匿名類被寫入的上下文(靜態或非靜態方法)。 但是看一下這部分代碼:
public class A {
int fieldOfA;
private static class B {
int fieldOfB;
}
public static void main(String[] args) {
B obj = new B() { //this anonymous class is static becuase is in the main method.
private static void testMethod() { //so why here i have an error and i can put just a non-static method
//if my class is static ?
//a class static can have static method, but this class no, why?
}
};
}
}
確保匿名類是靜態的?
如果上下文是靜態的,則匿名類是靜態的。 例如以靜態方法。
如果存在非靜態上下文,則匿名類是非靜態的,無論您是否需要它都是非靜態的。 如果不使用非靜態上下文,則編譯器不夠聰明,無法使類靜態化。
在此示例中,創建了兩個匿名類。 靜態方法中的一個沒有引用外部類,就像靜態嵌套類一樣。
注意:這些類仍稱為“內部”,即使沒有對外部類的引用也不能具有靜態成員。
import java.util.Arrays;
public class Main {
Object o = new Object() {
{
Object m = Main.this; // o has a reference to an outer class.
}
};
static Object O = new Object() {
// no reference to Main.this;
// doesn't compile if you use Math.this
};
public void nonStaticMethod() {
Object o = new Object() {
{
Object m = Main.this; // o has a reference to an outer class.
}
};
printFields("Anonymous class in nonStaticMethod", o);
}
public static void staticMethod() {
Object o = new Object() {
// no reference to Main.this;
// doesn't compile if you use Math.this
};
printFields("Anonymous class in staticMethod", o);
}
private static void printFields(String s, Object o) {
System.out.println(s + " has fields " + Arrays.toString(o.getClass().getDeclaredFields()));
}
public static void main(String... ignored) {
printFields("Non static field ", new Main().o);
printFields("static field ", Main.O);
new Main().nonStaticMethod();
Main.staticMethod();
}
}
版畫
Non static field has fields [final Main Main$1.this$0]
static field has fields []
Anonymous class in nonStaticMethod has fields [final Main Main$3.this$0]
Anonymous class in staticMethod has fields []
從JLS 15.9.5開始 :
匿名類始終是內部類(第8.1.3節); 它永遠不會是靜態的(第8.1.1節,第8.5.1節)。
第8.1.3節詳細討論了內部類,包括它們在靜態上下文中何時發生。 但是它們本身永遠不是靜態的,因此不能聲明靜態成員(常量變量除外)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.