• Post Reply Bookmark Topic Watch Topic
  • New Topic

location of main method declaration  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In my studies, I notice that the main( ) method can be declared in either a public class or a default-access class.
Is there a Java "convention" or "best practice" used by the Java development community in determining whether the main( ) method should be declared in a public class or not.

What criteria are used to make this decision?

Thank you.
ROW
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The convention is for it to be public.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Language Specification (the official specification of how Java works) describes in section 12.1.4:
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.

So, it says the main method must be public.

Some versions of Java also accept it if the main method has default access, but formally, that's wrong. Always make your main method public.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can declare main methods with any signature or modifiers, but only the main method with the requisite signature will be found by the JVM to start you application.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys, I think he was asking about the class containing main(), not main() itself.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're right Jeff. And I agree that the class that contains the main() method should be public, even though Java doesn't require this.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!