Why can't we define a top level class as private?

前端 未结 10 2094
情书的邮戳
情书的邮戳 2020-12-07 12:38

Why does Java not allow a top level class to be declared as private? Is there any other reason other than \"We can\'t access a private class\"?

相关标签:
10条回答
  • 2020-12-07 13:07

    Private classes are allowed, but only as inner or nested classes. If you have a private inner or nested class, then access is restricted to the scope of that outer class.

    If you have a private class on its own as a top-level class, then you can't get access to it from anywhere. So it does not make sense to have a top level private class.

    0 讨论(0)
  • 2020-12-07 13:19

    We can not declare an outer class as private. More precisely, we can not use the private access specifier with an outer class. As soon as you try to use the private access specifier with a class you will get a message in Eclipse as the error that only public, final, and abstract can be used as an access modifier with a class.

    Making a class private does not make any sense as we can not access the code of its class from the outside.

    0 讨论(0)
  • 2020-12-07 13:20

    Java doesn’t allow a top level class to be private. Only 'public' or 'package'.

    0 讨论(0)
  • 2020-12-07 13:24

    As we already know, a field defined in a class using the private keyword can only be accessible within the same class and is not visible to the outside world.

    So what will happen if we will define a class private? Will that class only be accessible within the entity in which it is defined which in our case is its package?

    Let’s consider the below example of class A

    package com.example;
    class A {
        private int a = 10;
    
        // We can access a private field by creating object of same class inside the same class
        // But really nobody creates an object of a class inside the same class
        public void usePrivateField(){
            A objA =  new A();
            System.out.println(objA.a);
        }
    }
    

    Field ‘a’ is declared as private inside ‘A’ class and because of it, the ‘a’ field becomes private to class ‘A' and can only be accessed within ‘A’. Now let’s assume we are allowed to declare class ‘A’ as private, so in this case class ‘A’ will become private to package ‘com.example’ and will not be accessible from outside of the package.

    So defining private access to the class will make it accessible inside the same package which the default keyword already does for us. Therefore there isn't any benefit of defining a class private; it will only make things ambiguous.

    You can read more in my article Why an outer Java class can’t be private or protected.

    0 讨论(0)
提交回复
热议问题