0

If I define a member variable inside static nested class in java like this:

public class Outer {

    public static class StaticNestedClass {
         private int mMember = 3;
    }

}

mMember would be interpreted static because its class is static? What about static nested class members in java?

Thanks in advance.

iberck
  • 2,372
  • 5
  • 31
  • 41

2 Answers2

7

No, static on a class doesn't have the same meaning as staticon a field. The field mMember is a private instance field of the nested class StaticNestedClass. You can use this nested class as if you were using any other top-level class, as long as you import it or use it with reference to its containing class, ie. Outer.StaticNestedClass. For example,

import Outer.StaticNestedClass;

...
StaticNestedClass instance = new StaticNestedClass();

or

import Outer;

...
Outer.StaticNestedClass instance = new Outer.StaticNestedClass();

An inner class cannot declare static members under some rules, see here.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

from the java doc

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.

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience. Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject =
     new OuterClass.StaticNestedClass();
stinepike
  • 54,068
  • 14
  • 92
  • 112