Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question about main method in java

 
Phani Kumar
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general when we write main method,we make it as public static void main.
but instead we can also write private static or protected static.
the code works fine.
please tell me what is the difference among these three?
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unfortunately, the case you describe is special, and you should not use this knowledge to think it works the same with other static methods.
The reason that main() can be private or protected is that the JVM uses this method as the starting point when it executes a java application.
If I have a simple class...
class Foo{
public static void main(String[] args)
{
System.out.println("I am foo");
}
}//end class Foo
and you run this by typing...
java Foo
The JVM will start a new user thread, and begin executing the main() method. Since the main() entry point must always be accessible to the JVM, it ignores the access modifier. So even if the main() method is made private, the JVM will still be able to execute it.
Again, this is a very special exception and you should not think this applies to any other method in java.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic