Why We declares main method always public ?

Because the rules of the JVM say that when it launches your program, it will look for a public main method in the class you give it.

The JVM could have been designed to not care if the method was public, but it's more consistent with the general use and purpose of the access levels. Whatever is invoking your main is not part of the same class or package, nor is it a subclass, so it makes sense that it should only invoke a public main method. Also, this lets you write a non-public main (though I wouldn't do it) and not have to worry that it will be used as an entry point to your program when it shouldn't be.

In the end, though, the real answer, as with all "Why is Java this way?" questions, is, "Because that's what the designers decided on." Unless we get hold of a white paper or their meeting minutes, we can't know what was in their minds. All we can do is examine pros and cons and take an educated guess that they saw the same pros and cons, and made their decision based on those pros and cons, and on what fits best with Java's overall goals, and on what they had the resources to implement in the schedule they were working with.

No comments:

Post a Comment