by Tony Sintes

The main method: Theory vs. reality

news
Jul 27, 20012 mins

Does the main method have to be public?

Q: I found that:

public static void main( String [] args )

works if it is declared as:

private static void main( String [] args )

A: If this is true, doesn’t this violate object-oriented programming’s concept of encapsulation? Moreover, how could a JVM check for the main() method if the access is private ? Why doesn’t it throw a runtime or a compile-time error?

Sun introduced this problem in version 1.2 of Java. As of 1.3 the problem is still there.

After a quick search for “private main” at java.sun.com, I found (requires login):

https://developer.java.sun.com/developer/bugParade/bugs/4252539.html

As you can see, the main 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.”

So there you have it.

However, be careful while taking the certification exam. Last time that I checked, the proper answer to “How do you define a main?” remains: “The method main must be declared public, static, and void.” Reality and the correct answer seem to disagree.

Tony Sintes is a principal consultant at BroadVision. Tony, a Sun-certified Java 1.1 programmer and Java 2 developer, has worked with Java since 1997.