Private class declaration [duplicate]

2019-03-14 11:18发布

Possible Duplicate:
Java: Why can we define a top level class as private?

Why can't we declare a private outer class? If we can have inner private class then why can't we have outer private class...?

6条回答
Lonely孤独者°
2楼-- · 2019-03-14 11:59

You can't have private class but you can have second class:

public class App14692708 {
    public static void main(String[] args) {
        PC pc = new PC();
        System.out.println(pc);
    }
}

class PC {
    @Override
    public String toString() {
        return "I am PC instance " + super.toString();
    }
}

Also remember that static inner class is indistinguishable of separate class except it's name is OuterClass.InnerClass. So if you don't want to use "closures", use static inner class.

查看更多
贪生不怕死
3楼-- · 2019-03-14 12:04

To answer your question:

If we can have inner private class then why can't we have outer private class...?

You can, the distinction is that the inner class is at the "class" access level, whereas the "outer" class is at the "package" access level. From the Oracle Tutorials:

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

Thus, package-private (declaring no modifier) is the effect you would expect from declaring an "outer" class private, the syntax is just different.

查看更多
乱世女痞
4楼-- · 2019-03-14 12:04

You can.

package test;

public class Test {
    public static void main(String[] args) {
        B b = new B();
    }
}

class B {
  // Essentially package-private - cannot be accessed anywhere else but inside the `test` package
}
查看更多
爷、活的狠高调
5楼-- · 2019-03-14 12:12

private makes the class accessible only to the class in which it is declared. If we make entire class private no one from outside can access the class and makes it useless.

Inner class can be made private because the outer class can access inner class where as it is not the case with if you make outer class private.

查看更多
老娘就宠你
6楼-- · 2019-03-14 12:20

Private outer class would be useless as nothing can access it.

See more details:

Java: Why can we define a top level class as private?

查看更多
三岁会撩人
7楼-- · 2019-03-14 12:22

private modifier will make your class inaccessible from outside, so there wouldn't be any advantage of this and I think that is why it is illegal and only public, abstract & final are permitted.

Note : Even you can not make it protected.

查看更多
登录 后发表回答