Can a Static Nested Class be Instantiated Multiple Times?

前端 未结 6 1033
别那么骄傲
别那么骄傲 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:52

    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.

提交回复
热议问题