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 Can there be only one public  class in a file 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 "Can there be only one public  class in a file" Watch "Can there be only one public  class in a file" New topic

Can there be only one public class in a file

Kumar Kausikasa
Ranch Hand

Joined: Jun 04, 2002
Posts: 45

I have a simple Question . Can there be only one "public class" in a file ?
I did some sort of this , but it complained .
import java.util.*;
public class MyTest
public static void main (String[] args)
FirstClass fs = new FirstClass();
SecondClass sc = new SecondClass();
System.out.println("This Works--sai");
Public class FirstClass
public FirstClass(){}
public class SecondClass
public SecondClass() {}
C:\praveen\DisMDSets\mandelbrot>javac 'class' or 'interface' expected
Public class FirstClass
^ class SecondClass is public, should be declared in a file named
public class SecondClass
2 errors
Can someone explain further? or point to me a link.
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
Only one public class is allowed per file and the file must have the same name as the class.

[Blog] [Blogroll] [My Reviews] My Linked In
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
From the JLS:

When packages are stored in a file system (�7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:
The type is referred to by code in other compilation units of the package in which the type is declared.
The type is declared public (and therefore is potentially accessible from code in other packages).
This restriction implies that there must be at most one such type per compilation unit
I agree. Here's the link:
subject: Can there be only one public class in a file
It's not a secret anymore!