• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubts about the class containing main method

 
Tonguc Koc
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

having no professional experience on Java, I decided to prepare for the OCA7 exam 2 weeks ago. I've a doubt about the following example, I hope you can help me to clarify:


This code piece in PublicClass.java file compiles fine and runs without any problem and prints "JavaRanch". Here in this example, main method is in a package protected class. Can we say that there is no such rule which mandates the main method to be in a public class? On the other hand I'm not sure how java finds the main class and executes it successfully.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, if there was such a rule then it wouldn't have worked! The relevant section in the Java Language Specification is here - http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html - and that doesn't seem to mention any requirement for the main method to be public.

As to how Java find the main class? You tell it which one to use - it's part of the command line. Or maybe it's in the manifest if you make an executable JAR file. Either way, there's no problem having lots of files with main methods, and Java runs the one you tell it to.
 
Tina Smith
Ranch Hand
Posts: 208
9
Eclipse IDE Firefox Browser Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, the main method is package-accessible (at least the way I read your statement), not package protected. Protected classes are package + inheritance, package level classes are package only. Could just be a matter of my interpretation but since this is a certification forum wanted to make sure it was mentioned.

You are correct, there is no rule that requires the main method to be in a public class.
I really like this description of why the main method is declared exactly the way it is. http://howtodoinjava.com/2012/11/02/a-mini-guide-to-main-method-in-java/

The one sentence summary of that post is that the method declaration is used within the compiled class to find main and execute it. (Which is why main must be declared exactly).

 
Tonguc Koc
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, it is pretty clear now.

BTW thanks Tina for the correction. I noticed that I'm using the wording "package-protected" instead of "package private".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic