Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

class has to be public

 
Arnb Sen
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Is it necessary that the class in which the main() is defined have to be public ?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a somewhat grey area. Technically, I believe the answer is "yes". Practically, it's "no" -- most Java implementations will run your class whether its public or not.
 
Arnb Sen
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so if we have this question during certification exam, what option are we supposed to select ?
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They won't ask you that question.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[EFH]: Technically, I believe the answer is "yes".

I don't think it is. It's required that the main() method be public (which was originally not enforced by Sun's JVMs, but has been enforced since 1.4 I believe). However I don't see any requrement that the class be public. In fact the JLS has several examples in which the class is not public, but rather package. So I would say that the JVM is required to allow this. And testing confirms this is what JDK 5 does, at least.

So...

[Arnb]: Is it necessary that the class in which the main() is defined have to be public ?

No.
[ September 03, 2005: Message edited by: Jim Yingst ]
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>> Is it necessary that the class in which the main() is defined have to be public?

Yes, it is required. JVMs prior to 1.4 had a bug that allowed non-public main methods to be run. The reaction was appropriate: massive yawn, will not fix.

http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.1.4

This will fail with "main method not public".

class foo { static void main(String ... args) { } }
[ September 03, 2005: Message edited by: Rick O'Shay ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Rick - as I noted. But the question is about whether the class needs to be public. Not the method.
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>> But the question is about whether the class needs to be public. Not the method.

I know, I was just testing you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic