Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

java - scope of private constructor in Nested Class

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

public class PrivateBaseConstructor {
    public static class BaseClass {
        private BaseClass() {
        }

    }

    public static class DerivedClass extends BaseClass {
        public DerivedClass() {
            super(); // 1*
        }
    }
}

Here the call for super(); at 1* is allowed even though the base class constructor is private. If we write the classes as separate classes in same package:

BClass.java
public class BClass {
    private BClass() {

    }
}

DClass.java
public class DClass extends BClass {
    public DClass() {
        super(); // 2*
    }

The compiler rightly gives an error at 2* since the base class constructor is not visible.

Why doesn't the compiler throw an error in my first scenario when both the classes are declared static within one class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...