Why can't a class or an interface receive priv

2019-01-21 10:51发布

I am reading some Java text and the text says that we can only apply public or default access modifier for class and interface. Therefore, it is a compiling error if we declare:

private class A {}

or

protected class A{}

I am just curious why a class or an interface cannot receive private or protected access modifiers?

3条回答
不美不萌又怎样
2楼-- · 2019-01-21 11:14

private means "only visible within the enclosing class".

protected means "only visible within the enclosing class and any subclasses, and also anywhere in the enclosing class's package".

private, therefore, has no meaning when applied to a top-level class; the same goes for the first part of the definition of protected. The second part of protected could apply, but it is covered by the default (package-protected) modifier, so protected is part meaningless and part redundant.

Both private and protected can be (and frequently are) applied to nested classes and interfaces, just never top-level classes and interfaces.

查看更多
混吃等死
3楼-- · 2019-01-21 11:16

top level classes can only have public or default access, but internal classes can have private access:

public class TestClassAccess
{
    public static void main(String[] args)
    {
        new TestClassAccess().new TestClassPrivateAccess();
    }

    private class TestClassPrivateAccess
    {
        TestClassPrivateAccess()
        {
            System.out.println("I'm a private class");
        }
    }
}
查看更多
叼着烟拽天下
4楼-- · 2019-01-21 11:32

There are only two use cases for class visibility at the top level (a) Visible everywhere (b) Visible only within the package. Hence only two modifiers (public and default). If class is public, then it is visible to all classes. If there is no access modifier, then it is visible only for classes within the same package.

Had there been more use cases for class visibility at top level, Java language would have provided more modifiers.

查看更多
登录 后发表回答