Java - 匿名类是静态的还是非静态的

时间:2013-12-12 21:44:19

标签: java static-class

我知道这取决于编写匿名类的上下文(静态或非静态方法)。 但看看这部分代码:

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?
            }
        };
    }
}

确定匿名类是静态的吗?

2 个答案:

答案 0 :(得分:3)

如果上下文是静态的,则匿名类是静态的。例如用静态方法。

如果存在非静态上下文,则匿名类是非静态的,无论您是否需要它是非静态的。如果不使用非静态上下文,编译器就不够聪明,不能使类静态。

在此示例中,创建了两个匿名类。静态方法中的一个没有引用外部类,就像一个静态嵌套类。

注意:这些类仍称为“内部”,即使它们没有引用外部类,也不能拥有静态成员。

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 []

答案 1 :(得分:2)

来自JLS 15.9.5

  

匿名类始终是内部类(第8.1.3节);它永远不会是静态的(§8.1.1,§8.5.1)。

部分8.1.3更多地讨论内部类,包括它们何时出现在静态上下文中。但它们本身并不是静态的,因此不能声明静态成员(常量变量除外)。

相关问题