3

Even though I have done bit of coding in java, I'm still finding it hard to understand this basic concept. When I was going through a book I came across this line,

main( ) must be declared as public, since it must be called by code outside of its class when the program is started.

What does the author mean by saying code outside of its class?

ngesh
  • 13,398
  • 4
  • 44
  • 60
  • 1
    @MByD.. i'm not asking who is calling it.. i know JVM calls it.. but i did't know code Outside means that its the JVM.. – ngesh Aug 17 '11 at 11:52
  • 1
    As the OP says, this is a question about **the interpretation of this particular sentence** in a book, not whether or not it is actually the JVM that calls the method. (It's even evident from the title of the question.) – aioobe Aug 17 '11 at 11:55
  • @aioobe - I maybe got confused because of the question "which code is calling it..?". anyway, sorry, it just sounded like a duplicate to me. – MByD Aug 17 '11 at 12:01
  • @MByD.. and people just followed you by not even reading the question...:) – ngesh Aug 17 '11 at 12:03
  • @MByD, no prob... actually the question is slightly ambiguous. a bit frustrated as this is the second question that [gets closed](http://stackoverflow.com/questions/7088814/what-does-getters-setters-method-do-in-java-how-are-they-different-from-normal/7088834#7088834) today, for poor reasons (imo) :P – aioobe Aug 17 '11 at 12:03

6 Answers6

8

what do the author mean by saying code outside of its class.. which code is calling it..?

It is the JVM that calls the method, so, yes, "outside of its class" should in this case be interpreted as "by the JVM".

Technically speaking, the JVM is not a part of the class containing the main method, thus the method has to be public for it to call it.

aioobe
  • 413,195
  • 112
  • 811
  • 826
2

Directly JVM is calling this class without creating instance of this class so it is static.

when you run that class under the cover your OS receives this command

java YourMainClass

here java is an executable that your OS knows where it is and YourMainClass is the argument to the java it loads the class and searches & invokes the main method

Since it is JVM calling so public , Since it isn't creating any instance of the object it is static

jmj
  • 237,923
  • 42
  • 401
  • 438
1

The main() method is invoked by the JVM.

Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
0

Another class not in this package or the JVM itself.

Michael-O
  • 18,123
  • 6
  • 55
  • 121
0

The main function is the entry point of your program. If this function is not public and static your program can not be started.

RED SOFT ADAIR
  • 12,032
  • 10
  • 54
  • 92
0

If you are interested in the low level stuff check this: http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html

LordDoskias
  • 3,121
  • 3
  • 30
  • 44