multiple classes in a single file : modifier private not allowed here

前端 未结 7 1745
暗喜
暗喜 2021-02-12 14:38

I am not able to understand why this code doesn\'t compile:

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

p         


        
7条回答
  •  礼貌的吻别
    2021-02-12 15:25

    private and protected are meaningless to be allowed to a top level(not member) class/interface.

    They are applicable only to the class members which can be variables, constants, constructors, methods, classes, and interfaces.

    Why:

    (1) private: What may be the meaning/purpose if we define a class as private. Its scope should be private to some area. default access is already package private. And nobody wants a class to be source file private, (Guessing the reason) it may not be a good programming practice to allow because java applications are finally organized in the form of packages, but not in terms of source files. Any source file should be part of some package, so in broad/final view each class/interface is part of some package, not just of some .java file. So not applicable.

    (2) protected: If something is protected it should be available only within package and only to the sub classes in other packages. To extend a class in a different package, it should be available to all the classes in other packages, but protected says class should be available only to the classes extended it. It's a kind of deadlock situation. So not applicable.

    Source: My readings and understanding

提交回复
热议问题