aspose file tools*
The moose likes Beginning Java and the fly likes Is private allowed as modifier for main? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Is private allowed as modifier for main?" Watch "Is private allowed as modifier for main?" New topic
Author

Is private allowed as modifier for main?

Chandra Bairi
Ranch Hand

Joined: Sep 12, 2003
Posts: 152
Is private allowed as modifier for main? if so then why is it recommended that we have the following signature for main
public static void main(String[] s)
Why is private allowed? I have read in a site that to make the JVM tolerant. what does that mean?


Thanks,
Shekar
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

There's nothing special about the name "main." You can have functions named

or whatever you want.
But, by convention, the "java" command-line tool looks for a method declared as "public static void main(String[])" to invoke when you pass it a class name. If the signature is different, it may, or may not, work. It's just a convention, not a strict rule.


[Jess in Action][AskingGoodQuestions]
Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524
But, by convention, the "java" command-line tool looks for a method declared as "public static void main(String[])" to invoke when you pass it a class name. If the signature is different, it may, or may not, work. It's just a convention, not a strict rule.
it may
Could you please explain this. How can it get executed even the main method signature is not the conventional one(public static void main(String arg[]).
Thank you.


SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

The interpreter could still execute it if it were protected, default-protected, or private; there's nothing to stop an implementation of the Java command-line executable from calling java.lang.reflect.Method.setAccessible(true) on the Method object that represents a private version of main(). But it's not guaranteed to work.
There's probably no implementation of Java in existence that would still launch main() if the return type or argument types were different, but again, that's just by convention; there's nothing stopping me from writing a version that found any method named main(), and called it regardless of its signature. But changing the protection was all that the original poster was asking about.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Is private allowed as modifier for main?