Package-private class in a .java file - why is it available?

Consider the following code in which the HelloWorld class has default access or batch access:

 class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } } 

And suppose the above code is saved in a file called HelloWorld.java . So my question is: since HelloWorld now a private class package, how does it work? The main() method should not be visible or accessible through packages, right?

It makes sense to me if the HelloWorld class is declared public. Confusion occurs only when it is advertised using the default private package.

+3
java jvm package
03 Oct 2018-11-11T00:
source share
4 answers

Starting the JVM is described in ยง12.1 Starting the JLS virtual machine .

Note that this chapter does not say anything about visibility checks for a class. It only indicates that the main method should be public .

This means that there is simply no check for visibility at the class level (what type makes sense, since the context has not yet been set to check for visibility: in which โ€œpackageโ€ is โ€œcallingโ€?).

+6
03 Oct '11 at 11:12
source share

The main method will not be visible to other classes that are in different packages. But the JVM can see it all. You can easily find your main method and run it for you.

If you want to simulate access restriction, write another class in another package and try calling HelloWorld.main and see if the compiler works.

+1
Oct 03 2018-11-11T00:
source share

You did not make it very clear, but I assume that your question is why this main method can be started when java HelloWorld entered on the command line.

The answer is that the Java Language Specification simply does not require the class containing the main method to be publicly available. Access modifiers are a language engine designed primarily to provide support through encapsulation. They are not a security feature and, of course, not the unshakable laws of physics. The JVM launch mechanism simply ignores them.

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

+1
03 Oct '11 at 11:12
source share

Probably, the JLS developers decided that there is no need to restrict access to the main method if you know the name of the class, while at first glance it looks counter-intuitive; on the other hand, access can always be obtained through reflection, therefore it cannot be regarded as a security hole ... In any case, for example. By creating a facade for the private class of the package, we will indirectly touch on this ... Thus, protection is more likely against misuse and for further changes.

+1
Jun 02 '12 at 18:24
source share



All Articles