• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Can there be only one public class in a file

 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Only one public class is allowed per file and the file must have the same name as the class.
 
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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

 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic