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

前端 未结 10 2143
情书的邮戳
情书的邮戳 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条回答
  •  旧时难觅i
    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.

提交回复
热议问题