嵌套类中的私有构造函数的作用域 [英] scope of private constructor in Nested Class

查看:176
本文介绍了嵌套类中的私有构造函数的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这比问题更像是一个拼图。我有以下代码:

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*
        }
    }
}

调用 super(); 在1 *是允许的事件,尽管基类构造函数是 private 。如果我们将类作为单独的类写在同一个包中:

Here the call for super(); at 1* is allowed event 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*
    }

编译器在2 *处提供错误,因为基类构造函数是不可见的。

The compiler rightly gives error at 2* since 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?

推荐答案

如果成员或构造函数被声明为私有的,那么只有当它出现在包含声明的顶层类(§7.6)成员或构造者。

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

这篇关于嵌套类中的私有构造函数的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆