File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes public class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "public class" Watch "public class" New topic

public class

neha shrivastava

Joined: Sep 04, 2006
Posts: 1
i'm using jdk1.5 n i used 3 classes in one source file n not declared the class as public in which main method is there.but it still works n gives is it possible.
Kaarthick Ramamoorthy

Joined: Sep 01, 2006
Posts: 23

1) A class that has main method, need not be public. It may use default modifier.

2) A sourcefile may have any number of non-public class. If it has a public class, it must be the name of the file.

So in your case, all classes are non public and even non public class may contain main(). So no problem.

Hope you underdsood.
Srinivas Kalvala
Ranch Hand

Joined: Oct 20, 2005
Posts: 257


Its not compulsory that a public method should present in the java source file.

Note: If public class presents then only one class for one source allowed and the name of the source file must match.

Javac will generate .class files for all classes which are coded in the source file and you can have main in each and every class, there is no problem in that.

It will take the main from the class which , will be mentioned at java <className>
Vaibhav Chauhan
Ranch Hand

Joined: Aug 16, 2006
Posts: 115
its not a mandatory rule that a class containing main method should have access modifier as public....the rules are as following:

1. class in a file can have access modifier as either public or default.
2. if there are more than one class in a file one class can be public at max(but public access is not mandatory for any class even now).
3. the file name should match the public class.

i hope you are clear now.
I agree. Here's the link:
subject: public class
jQuery in Action, 3rd edition