Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static final field in public nested class

Tags:

java

eclipse

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.

like image 630
rocknow Avatar asked Aug 24 '12 08:08

rocknow


People also ask

Can static fields be final?

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).

Can nested class have static method?

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.

Can you access a public field through a static method of the class?

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.

Can inner class have static members?

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.


1 Answers

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.

like image 131
Sumit Singh Avatar answered Sep 18 '22 20:09

Sumit Singh