Package-private class within a .java file - why is it accessible?

前端 未结 4 1404
春和景丽
春和景丽 2020-12-17 06:19

Consider the following code, where the HelloWorld class has default or package-private access:

class HelloWorld {
    public static void main(St         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 06:36

    You have not made it very clear, but I assume that your question is why that main method can be run when you type java HelloWorld at the command line.

    The answer is that the Java Language Specification simply does not require the class that contains the main method to be public. Access modifiers are a language mechanism mainly intended to help maintainability via encapsulation. They're not really a security feature, and certainly not unshakable laws of physics. The JVM startup mechanism simply ignores them.

    In fact, you can even use a private inner class, and it will still run.

提交回复
热议问题