Can a Static Nested Class be Instantiated Multiple Times?
Asked Answered
F

6

25

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.

Faircloth answered 27/4, 2010 at 7:50 Comment(11)
You could always try it and see if it compiles :-)Semiweekly
Why would you think that static inner classes are instance-controlled? This is a very interesting assumption, one that is perhaps worth investigating. Feel free to write as much as you want on how you understand things are, maybe it'll lead to more interesting discussions.Conciliator
Why would you think that the answer is no? Just because you can use "static" for the singleton pattern?Unkindly
@polygenelubricants, @Searles: the source of the confusion seems pretty obvious to me. A static field "exists only once", and that's a concept novice programmers learn very early. Static methods can be (mis)understood like that too (which leads to questions like "do a lot of methods make objects bigger?). No wonder someone would be unclear about the rather different meaning of the keyword when applied to nested classes.Leandraleandre
@Michael: very good point. This is a very good question now that I understand the source of the confusion.Conciliator
Interesting. It seems like it's time to deepen my understanding of 'static'. Here's what informs my understanding and I base my assumption on: a static loop variable, function variable, or class field transcends instance––it refers to the same data in memory regardless of class instance, function instance (i use the term lightly), or loop block instance (again, 'instance' used lightly-cant think of a more proper term). Static class fields and member functions are independent of instance. In all these cases 'static' seems to reference something that transcends instance and is singular.Faircloth
Thus, leading to my assumption that a static nested class would be singular.Faircloth
@stormin986: note that there are no static loop variables or function variables in Java - only fields, methods and nested classes can be static.Leandraleandre
The best answer to this type of question is "try it and see"Sanious
@stormin986: the best (and correct) way to think about static is that it belongs to the type, not instances of the type.Conciliator
Thanks everyone, this has been a very helpful discussion.Faircloth
C
36

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

See also


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.

JLS 8.1.3 Inner Classes and Enclosing Instances

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.

See also

Conciliator answered 27/4, 2010 at 7:54 Comment(4)
Thanks! When I first think about it as I described in my comments on my question, my thought was "whatever is static is singular despite the enclosing context's instance". Now as I carefully consider your definition of 'static', I am re-defining my understanding of the term to be "whatever is static exists independently of the enclosing context's instance"––thus, a static nested class exists apart from an instance of it's parent class. And I believe this understanding of it would apply to static in the context of loop variables, function variables, and class members.Faircloth
And the more I think about it: relating the idea of 'singular' to 'static' is a subtle error to make. The only reason loop variables, function variables, and class fields were occurring to me as singular is because they are declarative statements, NOT type definition statements. Thus, a static class is the only thing (immediately coming to mind, at least) that is both static and able to be used to define new objects.Faircloth
@stormin986: maybe ask another question, "What does static mean?".Conciliator
polygenelubricants, just to double check I added a field "state" to the nested class and everything keep worked. cheersMaxon
M
6

@polygenelubricants : But in general, yes, a static nested type can be instantiated multiple times.

Just to be sure 100% of that I extended your snippet:

public class MultipleInner {
    static class Inner {
        private int state;
        public int getState() { return state; }
        public void setState(int state) { this.state = state; }
    }

    public static void main(String[] args) {
        List<Inner> inners = new ArrayList<Inner>();
        for (int i = 0; i < 100; i++) {
            Inner inner = new Inner();
            inner.setState(i);
            inners.add(inner);
        }
        for (Inner inner : inners) {
            System.out.println(inner.getState());
        }
    }
}

And of course the result is:

0
1
2
3
.
.
.
97
98
99
Maxon answered 19/4, 2011 at 1:17 Comment(0)
V
3

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.

Video answered 27/4, 2010 at 7:59 Comment(0)
W
0

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

Wieche answered 27/4, 2010 at 7:58 Comment(0)
E
0

Inner class can use non static members/methods of containing class. It can use them only through an object reference of the enclosing class-

     public class MultipleInner {
      private int outerstate =10;
      static class Inner {
        private int state;
        public int getState() { return state; }
        public void setState(int state) { this.state = state; }
      }

     public static void main(String[] args) {       
        Inner inner = new Inner();
        inner.setState(new MultipleInner().outerstate);
        System.out.println(inner.getState());        
     }

}

So, inner class doesn't have to pay the price of not being able to access the non static members of the enclosing class.

Ezar answered 29/5, 2013 at 10:18 Comment(0)
C
0

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 :

public class OuterClass {
    String outerStr = "this is the outer class!!" ;
    public static class StaticNestedClass {
        String innerStr = "default / first instance" ;      
    }

    public static void main(String[] args) {
        OuterClass.StaticNestedClass nestedObject1 = new OuterClass.StaticNestedClass();        
        OuterClass.StaticNestedClass nestedObject2 = new OuterClass.StaticNestedClass();
        nestedObject2.innerStr = "second instance" ;
        System.out.println(nestedObject1.innerStr) ;
        System.out.println(nestedObject2.innerStr) ;
    }
}

output:

default / first instance 
second instance
Contemporize answered 20/4, 2019 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.