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.
No, absolutely not - and it's not a convention. static and final are entirely different things. static means that the field relates to the type rather than any particular instance of the type. final means that the field can't change value after initial assignment (which must occur during type/instance initialization).
Static Nested Classes As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
You cannot access a non-static field from a static method, unless you first create an instance and access that instance's field. You can return the instance from the static method, so that the caller can see the set instance field.
Since inner classes are associated with the instance, we can't have any static variables in them. The object of java inner class are part of the outer class object and to create an instance of the inner class, we first need to create an instance of outer class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With