公共嵌套类中的静态final字段

roc*_*now 18 java eclipse

我有这样的代码:

public class Foo {
    public class Bar implements Parcelable {
        public static final Parcelable.Creator<Type> CREATOR =
                   new Parcelable.Creator<Type>() {
                   @Override
                   ....
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Eclipse说:

The field CREATOR cannot be declared static in a non-static inner type, unless 
initialized with a constant expression
Run Code Online (Sandbox Code Playgroud)

请告诉我它是什么?我认为这是因为我有嵌套类但不知道如何纠正错误.

Sum*_*ngh 25

内部类(非静态嵌套类)不能有任何静态方法.因为

An inner class is implicitly associated with an instance of its outer class, it cannot define any static methods itself.

对于外部类Foo,您可以访问如下静态方法test():

Foo.test();
Run Code Online (Sandbox Code Playgroud)

对于静态内部类Bar,您可以innerTest()像这样访问其静态方法:

Foo.Bar.innerTest();
Run Code Online (Sandbox Code Playgroud)

但是,如果Bar不是static,则现在没有静态方法来引用该方法innerTest().非静态内部类与其外部类的特定实例相关联.


Jac*_*erk 1

内部类不能有静态方法...如果你想拥有它,你也需要将 Bar 定义为静态。

否则,该字段必须声明为非静态的。