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.
A static inner class can be instantiated without the need for an instance of the outer class. In general, an Inner class is a part of nested class, called Non-static nested classes in Java. The types of inner classes are member inner class, anonymous inner class, and local inner class.
Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it's explicitly passed in a method parameter.
A class can be nested up to any depth; there is no practical limit, but a class nested deeper that two is almost always unnecessary.
Which statement is true about a static nested class? You must have a reference to an instance of the enclosing class in order to instantiate it. It does not have access to nonstatic members of the enclosing class. It's variables and methods must be static.
Yes, there is nothing in the semantics of a static
nested type that would stop you from doing that. This snippet runs fine.
public class MultipleNested { static class Nested { } public static void main(String[] args) { for (int i = 0; i < 100; i++) { new Nested(); } } }
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 a static 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.
An inner class is a nested class that is not explicitly or implicitly declared
static
.
That is, according to JLS terminology, an inner class is one that isn't static
. If it's static
, 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.
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