Can a Static Nested Class be Instantiated Multiple Times?

前端 未结 6 1030
别那么骄傲
别那么骄傲 2021-02-05 05:14

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 ne

6条回答
  •  隐瞒了意图╮
    2021-02-05 05:37

    @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 inners = new ArrayList();
            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
    

提交回复
热议问题