Saturday, April 11, 2009

The private main method

YES…!!!! the main method in java can be private.
I came across a good article while surfing on the net about main method being private. That means it works if written as: private static void main( String [] args )

Moreover, this method can also be activated by the VM, which actually breaks the encapsulation law. Actually, Sun introduced this problem in version 1.2 of Java and was not solved till 1.3. This is the case on MS Windows NT, Linux and Solaris. However, while running this code on Windows 2000 or XP gives the proper run time exception as "Main method not public".

check it on: http://developer.java.sun.com/developer/bugParade/bugs/4252539.html

This issue is a known problem with a bug report opened against it. However, Sun has closed the bug report and the problem will NOT be fixed, "The runtime allows call to private methods, because of reflection. Fixing it will cause potential troubles." This violates oop's basic concept, i.e. data encapsulation, you can declare the method as private to restrict its access from outside the class where it is declared, but in this case you can declare main method as private and still jvm can access the method. This is also a compatibility issue: with some JVM this work, but other JVMs might be confused.

However, this is not a big issue as only JVM can give the call to private main method and any other attemp to access it, will result in the compile time error.

I don't know whether the bug has been solved or not but it was giving runtime exception on my machine (XP) "Main method not public" and it might get execute on Solaris or Linux machine. But be careful while taking the certification exam. The proper answer to "How do you define a main method?" remains: "The method main must be declared public, static, and void."

No comments:

Computers Add to Technorati Favorites Programming Blogs - BlogCatalog Blog Directory