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.

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.