Given what I know of every other type of static feature of programming––I would think the answer is 'no'. However, seeing statements like OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
makes me wonder.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Yes, there is nothing in the semantics of a
static
nested type that would stop you from doing that. This snippet runs fine.See also
public static interface Map.Entry<K,V>
public static class AbstractMap.SimpleEntry<K,V>
Now, of course the nested type can do its own instance control (e.g.
private
constructors, singleton pattern, etc) but that has nothing to do with the fact that it's a nested type. Also, if the nested type is astatic enum
, of course you can't instantiate it at all.But in general, yes, a
static
nested type can be instantiated multiple times.Note that technically, a
static
nested type is not an "inner" type.JLS 8.1.3 Inner Classes and Enclosing Instances
That is, according to JLS terminology, an inner class is one that isn't
static
. If it'sstatic
, then it's just a nested type.So what does
static
mean?static
simply means that the nested type does not need an instance of the enclosing type to be instantiated.See also
Just to be sure 100% of that I extended your snippet:
And of course the result is:
Inner class can use non static members/methods of containing class. It can use them only through an object reference of the enclosing class-
}
So, inner class doesn't have to pay the price of not being able to access the non static members of the enclosing class.
Yeah you can make instances of it as many times as you want.
Maybe the reason why you see that, is because the programme thought about storing a reference somewhere. Though i agree with you seems strange :S
It is legal. The fact that the inner class is static gives you a benefit here; its instances are not bound to any instance of the containing class, so they can be freely instantiated (as long as the access qualifier allows it).
The price, however, is that the inner class can't use non static members/methods of the containing class.
Static nested classes are indeed instanced - they are, as said, top-level classes which live in the namespace of the 'outer' class, and obey static semantics respecting references to the 'outer' class. This code sample demonstrates :