Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JVM and private methods

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 .

like image 773
AllTooSir Avatar asked Jan 25 '12 06:01

AllTooSir


1 Answers

It is all about convention. The JVM can call every method everywhere - it is the JVM, the Boss. If the JVM can't call it, nobody can. Imagine the JVM is the place were your program gets executed, it is some kind of a proxy between you and your bytecode.

writeObject might not be of use outside your class. It is an internal only method, just for you. Thus the makers of the JVM agreed to leave it private. If it is not private, other classes in your program are able to call it.

The main() Method is a method which might be called by other Java processes. If it is private, other programs are unable to start your program. It has not much to do with the JVM, except you could say that normally the JVM allows you (!) to only call public (package, protected) methods of your code.

like image 91
Christian Avatar answered Nov 02 '22 22:11

Christian