I am a beginner in Java . The first thing I learned was the main() method of an executable class should be public and the reason given was since this method will be called by the JVM it should be visible outside the class and hence should be public. Now while studying serialization I find that the writeObject() and readObject() private methods of a Serializable class can be called by the JVM while serializing and de-serializing an object ! If they are private methods then how can JVM call them ? If it can then why it can’t call the main() method ?
After flipping through some java documentation , I read this line ” JVM can access private methods of an object ” . Since we call readObject() using an instance of ObjectInputStream so it is accessible to JVM , whereas main() method being a static or class method and called without instantiating any object of the class should be public in order to be accessible to JVM ! Does that make sense ? I don’t know .
Well in general I agree with @Christian, but I have 2 more notes:
The main() function could be also made private.
You can also call private method/function, if you really need.
1 JVM could call main() anyway. Making it public enables another code of your application to call main() method also. Normally, nobody does it, however. The main reason, why main() is public, is historic one, AFAIC. Other program languages also have main() function and there it is public.
2 If you really need, you can use Core Reflection API in order to call private method or to access private field. It looks something like this:
http://www.jguru.com/faq/view.jsp?EID=321191
See also this great answer https://stackoverflow.com/a/2489644/1137529