• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

public class or not

 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys:
The class in a file that has the main() method: Is it required to be public and only public
in that file? I thought so all along the way
but then I saw code that had no public class
and it still runs....
Thanks
Barkat
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please show us your code, and rephrase your question a little.
-Barry
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main() method must be public (and static and void), but the class itself need not be.
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ron:
So if class with main() is not public, it is not
accessable from outside of package: True?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's correct.
If the class is public then it must be the only one that's public in the file. And the filename must be the same as the public classes name (with .java of course)
-Barry
 
Ian Wayne
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try this code:

Even though class TestMain is not public, it still works.
Yan
 
Whiz Kid
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In each Source File there can be one and Only One public class which hosts the main method.Thats the only way the runtime System and statrt working on your program.
There is no way a program w/o a public class can execute.is so can u please paste that code here.
Hope this helps.
Gowri
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A source file can have any number of top-level classes, but at most one of them can be public. If there is a public class, its name must match the name of the file.
Any class, public or not, can have a method with the signature
public static void main (String[] args)
and if you feed such a class to the java interpreter, that method will execute.
 
Ian Wayne
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no way a program w/o a public class can execute.

Hi Whiz,
Question is why the code I posted before works fine. Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic