简体   繁体   中英

static final field in public nested class

I have such code:

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

Eclipse says:

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

Please tell me what is it? I think it is because I have a nested class, but I don't know, how to correct the mistake.

A inner class (non-static nested class) can not have any static methods. because

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

For an outer class Foo , you can access a static method test() like this:

Foo.test();

For a static inner class Bar , you can access its static method innerTest() like this:

Foo.Bar.innerTest();

However, if Bar is not static , there is now no static way to reference the method innerTest() . Non-static inner classes are tied to a specific instance of their outer class.

The inner class cannot have static methods... If you want to have it, you need to define Bar as static as well.

Otherwise, the field must be declared as non-static.

Although I do not know why, static fields and methods in inner classes are prohibited by Java. The only way to work around this to declare a static inner class; or of course you can make your field in the nested class non-static.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM