This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
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
Author

Can there be only one public class in a file

Kumar Kausikasa
Ranch Hand

Joined: Jun 04, 2002
Posts: 45
Hi,

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.*;
import java.io.*;
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 MyTest.java
MyTest.java:14: 'class' or 'interface' expected
Public class FirstClass
^
MyTest.java:18: class SecondClass is public, should be declared in a file named
SecondClass.java
public class SecondClass
^
2 errors
C:\praveen\DisMDSets\mandelbrot>
Can someone explain further? or point to me a link.
Thanks
Praveen
Valentin Crettaz
Gold Digger
Sheriff

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.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[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
 
GeeCON Prague 2014
 
subject: Can there be only one public class in a file