公共嵌套类中的静态最终字段

2022-09-02 21:10:22

我有这样的代码:

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

日食 说:

The field CREATOR cannot be declared static in a non-static inner type, unless 
initialized with a constant expression

请告诉我这是什么?我想这是因为我有一个嵌套的类,但我不知道,如何纠正错误。


答案 1

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

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

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

Foo.test();

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

Foo.Bar.innerTest();

但是,如果不是 ,现在没有静态方法来引用该方法。非静态内部类绑定到其外部类的特定实例。BarstaticinnerTest()


答案 2

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

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


推荐