campo final estático en clase anidada pública

Tengo tal código:

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

Eclipse dice:

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.

preguntado el 24 de agosto de 12 a las 09:08

3 Respuestas

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.

Para una clase externa Foo, puedes acceder a un método estático test() Me gusta esto:


Para una clase interior estática Bar , puedes acceder a su método estático innerTest() Me gusta esto:


Sin embargo, si Bar no es 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.

Respondido 09 Feb 15, 04:02

"However, if Bar is not static, there is now no static way to reference the method innerTest(). " - but why would we need a estático way to reference the method? We could have referenced it like new Foo().Bar.innerTest(). ¿Por qué no? - Consuelo

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.

Respondido 24 ago 12, 09:08

I don't think defining Bar as static will allow one to have a static variable within it. Not working for me anyway. - Marvo

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.

Respondido el 22 de junio de 16 a las 16:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.