单个文件中包含多个类:此处不允许使用修饰符private [英] multiple classes in a single file : modifier private not allowed here

查看:791
本文介绍了单个文件中包含多个类:此处不允许使用修饰符private的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解为什么此代码无法编译:

I am not able to understand why this code doesn't compile:

class A {
    public static void main(String[] args) {
        System.out.println("hi");
    }
}

private class B {
    int a;
}

我将内容保存在名为A.java的文件中-并出现错误:

I am saving the contents in a file named A.java - and I get an error:

modifier private not allowed here // where I have defined class B

当我将B设为私有和受保护时,都会发生这种情况.有人可以解释一下这背后的原因吗?

This happens both when I try B as private and protected. Can someone please explain me the reason behind this?

谢谢!

推荐答案

来自

protected和private访问修饰符仅与直接包含在类声明中的成员类有关

The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration

是的,顶层声明不允许使用private和protected修饰符.

So yes, the private and the protected modifiers are not allowed for top level class declarations.

顶级类可以公开或不公开,而不允许privateprotected.如果将该类声明为public,则可以从任何包中引用它.否则,只能从同一包(命名空间)中引用它.

Top-level classes may be public or not, while private and protected are not allowed. If the class is declared public, then it can be referred to from any package. Otherwise it can only be referred to from the same package (namespace).

私有顶级类没有多大意义,因为任何类都不能引用它.根据定义,它将无法使用.对于成员类来说,private可以使一个类仅对其封闭类可引用.

A private top level class wouldn't make much sense because it couldn't be referred to from any class. It would be unusable by definition. private is OK for member classes to make a class referable to only it's enclosing class.

受保护的成员类可以从(1)同一包的任何类以及(2)封闭类的任何子类中引用.很难将这个概念映射到顶级类.第一种情况由顶级类覆盖,没有访问修饰符.第二种情况不适用于顶级类,因为没有封闭类或其他与该类有特殊关系的包中的其他东西(例如子类).因此,我认为protected是不允许的,因为它的基础概念不适用于顶级类.

A protected member class can be referred to from (1) any class of the same package and from (2) any subclass of the enclosing class. Mapping this concept to top level classes is difficult. The first case is covered by top level class with no access modifiers. The second case is not applicable for top level classes, because there is no enclosing class or something else from a different package with a special relation to this class (like a subclass). Because of this I think, protected is not allowed because it's underlying concept is not applicable for top level classes.

这篇关于单个文件中包含多个类:此处不允许使用修饰符private的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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