22

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

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

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

Thanks !

4

7 回答 7

27

来自Java 语言规范

访问修饰符 protected 和 private 仅适用于直接封闭类声明中的成员类

所以是的,顶级类声明不允许使用 private 和 protected 修饰符。

顶级课程可能是公开的或不公开的,而private不允许protected。如果该类被声明为公共的,则可以从任何包中引用它。否则只能从同一个包(命名空间)中引用。

私有顶级类没有多大意义,因为它不能被任何类引用。根据定义,它将无法使用。private成员类可以使一个类只能引用它的封闭类。

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

于 2010-08-16T06:55:34.790 回答
4

Make the B nested of A, like this:

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

    private class B {
        int a;
    }
}

Or move B to a separate file. Also you can stick with default access level, this way the class can be accessed only from within the package:

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

class B {
    int a;
}
于 2010-08-16T06:52:32.680 回答
1

private 和 protected 被允许进入顶级(非成员)类/接口是没有意义的。

它们仅适用于可以是变量、常量、构造函数、方法、类和接口的类成员。

为什么:

(1)私有的:如果我们将一个类定义为私有的,可能的含义/目的是什么。它的范围应该对某些区域是私有的。默认访问已经是包私有的。并且没有人希望一个类是源文件私有的,(猜测原因)这可能不是一个好的编程习惯,因为 Java 应用程序最终以包的形式组织,而不是源文件的形式。任何源文件都应该是某个包的一部分,因此在广义/最终视图中,每个类/接口都是某个包的一部分,而不仅仅是某个 .java 文件的一部分。所以不适用。

(2) protected:如果某些东西受到保护,它应该只在包内可用,并且只对其他包中的子类可用。要扩展不同包中的类,它应该对其他包中的所有类都可用,但受保护的类应该只对扩展它的类可用。这是一种僵局。所以不适用。

来源:我的阅读和理解

于 2014-02-01T12:44:48.343 回答
0

Just have no private/protected modifier at all.

于 2010-08-16T06:51:53.513 回答
0

B needs to be private to something. Place it within the definition of class A or create another file, B.java, and define it there, but then it cannot be private.

于 2010-08-16T06:52:09.107 回答
-1

如果您不对类使用 public 关键字,则默认情况下它将是私有的(仅在文件中可见)。

每个 .java 文件只能有一个公共类,其他所有类都必须是私有的。因此,A 类可以是公共的,B 类在您的示例中不需要任何修饰符。公共类名必须与.java 文件名匹配(例如,A.java 只能包含一个名为“A”的公共类)。

于 2010-08-16T06:53:59.363 回答
-2

A.java不能包含两个类。

于 2010-08-16T06:57:32.033 回答