scope of private constructor in Nested Class

前端 未结 3 1603
慢半拍i
慢半拍i 2020-12-14 16:09

This is more of a puzzle than question. I have the following code:

public class PrivateBaseConstructor {
    public static class BaseClass {
                


        
3条回答
  •  暖寄归人
    2020-12-14 16:47

    Because nested classes can see each others members. This has nothing to do with the static declarations. See the following example of your code with just nested inner classes (not static).

    public class PrivateBaseConstructor {
        public class BaseClass {
            private BaseClass() {}
        }
    
        public class DerivedClass extends BaseClass {
            public DerivedClass() {
                super(); // 1*
            }
        }
    
        public static void main(String[] args)
        {
           new PrivateBaseConstructor(). new DerivedClass();
        }
    }
    

    Read more about nested classes here: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

提交回复
热议问题