Can a Static Nested Class be Instantiated Multiple Times?

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

    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
    

提交回复
热议问题