Public class must be written in a seperate .java file?

Hi,
1. why is it compulsory for a public class to be written in a seperate .java source file?
2. why can not a .java source file contain more than one public classes?

Can you elaborate more on "to make it quicker for the compiler to import packages"Think what you'd do if you were the compiler and you needed to handle this code :
package my;
import my.gaphics.*;
import my.util.*;
class My {
  private Utility x;
}How do you work out where to look for the source of class Utility? If you insist that all public classes are declared in a file with the matching name then you only need to check whether my/graphics/Utility.java or my/util/Utility.java exists, and there you have your source. Otherwise you'd need to parse all imported packages upfornt, since you can't tell which file will contain the source of Utility.

Similar Messages

  • Why public class name should be same as the java file name

    Hi,
    I would like to know, why public class name should be same as the its java file name. Iam in the process of finding the answer to this question. Can someone help me out in finding the explanation.
    Thanks in advance,
    Manoj

    This is a requirement of the Java reference compiler released by Sun. I have used compilers that did not require this, but most seem to follow the reference compiler (which is a very good idea). I am NOT sure if this is specified in the Java Language Specification. Some of the other regulars who are more familiar with the JLS than I may be able to tell you.
    ? {?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Why it is necessary that public class name should  same as filename in java

    hi,
    why it is necessary that public class name should same as filename in java.
    As I know that it is a convention, but I want the information why this convention is made.
    thanx.

    user13445117 wrote:
    but suppose if i am creating a java file with default access modifire then we do not need to save the file name as a class name.So, your question is "Why does the rule about top-level classes being in a file of the same name apply +only+ to public classes"?
    If it were applied to all classes, then we could never have two top-level classes in the same file. Doing that is generally not a good idea, but it might be useful from time to time. EJP already told you why it applies to public classes, and, since these are the most common by far, it's a fair compromise that it apply to them but not to other classes.
    Was this the reason the original designers did it that way 15 or so years ago? Don't know, don't care, but it's one plausible explanation. Maybe it was just a balance between simplicity and clarity on the one hand, and flexibility on the other.
    It's certainly not something I can see caring that much about, unless you're doing an in-depth history on Java, or writing an in-depth treatise on computer language and compiler theory.

  • Compiling new classes on the fly without having a .java file

    Hi everybody,
    I'd like to compile dynamically produced JAVA code (code from user input in my application). I don't wanna store the source code in a .java file, but just compile the code (as char[] or something like that) to a byte[].
    Does anybody have an idea ??
    Thanks
    Jan

    Have you looked at the idea of interpreting rather than compiling, say using Jython (a python interpreter written in Java). Python and Java are extremely close in syntax, and it should be relatively easy to do what you are talking about.
    I am worried though, that you are going to let users type in text, and assume that it has valid syntax in the language you are using. Many years of UI experience indicate that letting users type in anything results in a certain error rate. Letting it be instructions you are to follow in your code is even more dangerous.
    There are many programs that let users define actions interactively. They seem to either let the user type in text, and error check it to death (a lot of work, think spreadsheet type programs), or they present the user with a set of choices, often using a wizard type interface, which takes more up front UI work, but only lets the users select valid options.
    It sounds like you want to interpret what the user types in as instructions. Even with Jython (or a similar interpreter), you would need to parse the user input for formatting errors, invalid variable names, and anything else they could make a mistake on, before you could pass any of it to the interpreter.
    Good luck.

  • Instantiating VHDL module written in a seperate .vhd file

    Hi,       I have two files in the pcores>hdl>vhdl folder 1) "vga_controller_vhdl.vhd"  the main file(created through EDK) which communicates with Microblaze through FSL and 2) "vga_controller_640_60.vhd" file that contains the timing generator module "vga_controller_640_60" .  Can someone point how I could link these two?       I have instantiated the vga_controller_640_60 module in the 1st file as follows   library vga_controller_vhdl_v1_00_a;
    use vga_controller_vhdl_v1_00_a.ALL;   architecture EXAMPLE of vga_controller_vhdl is
        component vga_controller_640_60
          port ( rst       : in    std_logic;
                 pixel_clk : in    std_logic;
                 hs        : out   std_logic;
                 vs        : out   std_logic;
                 blank     : out   std_logic;
                 hcount    : out   std_logic_vector (0 to 10);
                 vcount    : out   std_logic_vector (0 to 10));
       end component;
    begin
       VgaCtrl640_60 : vga_controller_640_60
          port map (pixel_clk=>CLK_25MHz,
                           rst=>FSL_Rst,
                           blank=>bitBlank640_60,
                           hcount(0 to 10)=>vecHcount_640_60(0 to 10),
                           hs=>HS,
                           vcount(0 to 10)=>vecVcount_640_60(0 to 10),
                           vs=>VS); --------- other code ---   end architecture EXAMPLE;     ----Contents of vga_controller_vhdl_v2_1_0.pao  ##############################################################################
    ## Filename:          G:\Electronics\FPGA\EDK_Projects\Test1\pcores/vga_controller_vhdl_v1_00_a/data/vga_controller_vhdl_v2_1_0.pao
    ## Description:       Peripheral Analysis Order
    ## Date:              Sat Dec 12 15:17:00 2009 (by Create and Import Peripheral Wizard)
    lib vga_controller_vhdl_v1_00_a vga_controller_640_60 vhdl          ## I added this line here
    lib vga_controller_vhdl_v1_00_a vga_controller_vhdl vhdl       When I compile I get this error:    'vga_controller_vhdl_0/vga_controller_vhdl_0/VgaCtrl640_60' with type
       'vga_controller_640_60' could not be resolved. A pin name misspelling can
       cause this, a missing edif or ngc file, or the misspelling of a type name.
       Symbol 'vga_controller_640_60' is not supported in target 'spartan3e'.
    make: *** [__xps/system_routed] Error 1    Regards,   Karthik

     I had initially added the  "lib vga_controller_vhdl_v1_00_a vga_controller_640_60 vhdl", at the end of the file and saw the error message. I corrected this by putting it before the main module's lib line. But the error persisted. Today morning, I used the "clean hardware" command and "rescanned the user peripheral" and it worked. It seems that  "clean hardware" is required whenever changing anything in the pcore other that the hdl code. EDK apparently scans only the hdl files for changes during compile.   ##############################################################################
    Filename:         
    G:\Electronics\FPGA\EDK_Projects\Test1\pcores/vga_controller_vhdl_v1_00_a/data/vga_controller_vhdl_v2_1_0.pao
    ## Description:       Peripheral Analysis Order
    ## Date:              Sat Dec 12 15:17:00 2009 (by Create and Import Peripheral Wizard)
    lib vga_controller_vhdl_v1_00_a vga_controller_640_60 vhdl          ## I added this line here
    lib vga_controller_vhdl_v1_00_a vga_controller_vhdl vhdl   Thanks guys.

  • Programatically executing a seperate java file

    Hey java forums! I need one of my programs to programatically run/execute a separate .java OR .class file that also has a main method. Can I and how do I do this? Thank you in advance!

    Also, you may need to use a URLClassLoader if the java class file you are trying to run is not on the classpath.
    You may want to set security permissions or a shutdown hook on the other app that you start so that if it calls system.exit, it doesn't shut down your main app.
    Finally, you can also use Runtime.exec to start another java app. This has the advantage of not needing the shutdown hook.

  • Why only 1 public class in java file

    In any java file, why do we have only one public class whose name is same as the java file name?

    Jasmit1986 wrote:
    Thanx for the link db. But in the link it is explained why we have the name of the java file same as the class name.
    My doubt is that why can't we have more than one public class in a java fileTo keep things simple and less confusing. There's really no good reason to have multiple public classes in one file, so this just enforces the "best practices" idea.

  • Why a single .java file can't have multiple public classes defined in it?

    A public class must be saved in a .java file with the same name, why?

    Tejaswi.Khijwania wrote:
    A public class must be saved in a .java file with the same name, why?This is what the JLS states (7.6 Top Level Type Declarations),
    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. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.
    As you can see a host system (development system) may enforce this restriction. It doesn't have to.

  • Can you have multiple classes in one .java file ?

    or am I being dumb ;-)
    I'm guessing not because the filename has to match the classname but maybe you can ... ?
    C

    To elaborate a bit more. The public class must match the filename, however you can declare "inner" classes.
    An inner class can be declared inside another class, or even inside another method. Where you declare that class dictates the scope it will have. However, the lack of an ability to declare these classes public (a public class must be declared inside a java file with the same name), means that they are not visible anywhere else. However, they do still have plenty of uses.
    Declaring a class inside a method is used rarely, but would look something like
    public void foo(Bar myBar = new Bar
            private String baz = "Hello";
            public String doSomething()
                 return baz;
         myBar.doSomething()
    }This declares and implements the class Bar inside the method header. Sure, this is a pretty useless example, but you could put any methods or variables inside your inner class, and they would be available only during execution of that method. (ie. only have method scope).
    }

  • How many classes should a .java file contain?

    Are there any general guidelines on how many Java classes should be contained in a single .java file? I've been creating a new .java file for each class I write but see examples in Sun's Java tutorial where there are at least two classes in a single .java file. One such case is the TableDemo example at
    http://java.sun.com/docs/books/tutorial/uiswing/components/example-swing/TableDemo.java
    Thanks.

    The example you point to isn't really more the one class in one java file. It makes use of an inner class. An inner class is something different! As far as I understand it, it is mainly used to implement some behaviour (in this case AbstractTableModel behaviour). If the MyTableModel was in a separate class file, it couldn't access the variable of the main TableDemo class. So they use an inner class.
    So unless you need inner classes, this example is no reason to put more than one class in a .java file. In general, just put one class in a .java file. It's easier for everybody.

  • How to get the .class file for the extended Controller .java file

    Hi,
    I did the below steps.
    1. Created New OAWorkspace
    2. Created New project
    3. Imported the page .xml file
    4. Added new .java file by extending the controller class
    5. Added code in the .java file.
    6. Ran the .xml file
    As I copied all the folders from Unix box, the page was opened.
    But My question was where can I see the .class file the extended controller. It's a .java file. How to compile and get the .class file for this .java file. If I get this .class file, I can go to the page and click the personlize page. and change the Controller name to the new path by ftp ing the new class to the cust.oracle.apps.pos.changeorder.webiui.
    Please let me know how to create the .class file.
    Thanks,
    HP

    All are Java files are stored in JDEV_INSTALL_DIR:\jdevhome\jdev\myprojects\
    In your case the path java would be
    JDEV_INSTALL_DIR:\jdevhome\jdev\ myprojects \cust\oracle\apps\pos\changeorder\webui\
    AND
    Once you compile the java file in Jdeveloper, Class files get generated @ below path
    In your case the path of class would be
    JDEV_INSTALL_DIR:\jdevhome\jdev\ myclasses \cust\oracle\apps\pos\changeorder\webui\
    Duplicate Thread-
    Thanks
    --Anil
    http://oracleanil.blogspot.com/

  • EJB Class loader and regular Java files class loader.

    Hi,
    Is the EJB's class loader the same as a "regular" java files class loader OR weblogic
    has 2 class loaders, one for each???
    Thanks,
    les.

    les <[email protected]> wrote:
    Hi,
    Is the EJB's class loader the same as a "regular" java files class loader OR weblogic
    has 2 class loaders, one for each???Yes. Exact classloading architecture depends on which WebLogic version you use. If you
    use 6.x+, you may want to read this article:
    http://www.onjava.com/pub/a/onjava/2001/07/25/ejb.html
    Thanks,
    les.--
    Dimitri

  • Rmic Public class com must be defined in a file called "com.java".

    Hello,
    After compiling with javac which works perfectly, rmic fails with the message below. I have added the -verbose flag in an attempt to make it more clear to me however, the error does't make sense, why would rmic complain about a missing '{' where javac wouldn't? Any thoughts on this would be greatly appreciated.
    [yourabi@happyending java]$ rmic -classpath $CLASSPATH:. -verbose -keepgenerated -nowrite com/jeteye/lucene/DistributedSearchFacade
    [loaded ./com/jeteye/lucene/DistributedSearchFacade.class in 22 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/rmi/server/UnicastRemoteObject.class) in 2 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/rmi/server/RemoteServer.class) in 0 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/rmi/server/RemoteObject.class) in 2 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/lang/Object.class) in 1 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/rmi/Remote.class) in 0 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/io/Serializable.class) in 0 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/lang/CloneNotSupportedException.class) in 0 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/lang/Exception.class) in 0 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/lang/Throwable.class) in 3 ms]
    [loaded ./com/jeteye/lucene/IRemoteIndex.class in 0 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/rmi/RemoteException.class) in 1 ms]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/io/IOException.class) in 4 ms]
    [found remote interface: com.jeteye.lucene.IRemoteIndex]
    [found remote interface: java.rmi.Remote]
    [string used for method hash: "index(Lcom/jeteye/domain/Jetpak;)V"]
    [string used for method hash: "deleteByAlias(Ljava/lang/String;)V"]
    [string used for method hash: "deleteByJPID(Ljava/lang/String;)V"]
    [string used for method hash: "dateSinceOptimized()Ljava/util/Date;"]
    [string used for method hash: "transactionsSinceOptimized()I"]
    [string used for method hash: "numTransactions()I"]
    [string used for method hash: "startp()Z"]
    [string used for method hash: "shutdown()Z"]
    [string used for method hash: "isStarted()Z"]
    [string used for method hash: "isShutdown()Z"]
    [string used for method hash: "optimize()Z"]
    [found remote method <0>: java.util.Date dateSinceOptimized() throws java.rmi.RemoteException]
    [found remote method <1>: void deleteByAlias(java.lang.String) throws java.rmi.RemoteException]
    [found remote method <2>: void deleteByJPID(java.lang.String) throws java.rmi.RemoteException]
    [found remote method <3>: void index(com.jeteye.domain.Jetpak) throws java.rmi.RemoteException]
    [found remote method <4>: boolean isShutdown() throws java.rmi.RemoteException]
    [found remote method <5>: boolean isStarted() throws java.rmi.RemoteException]
    [found remote method <6>: int numTransactions() throws java.rmi.RemoteException]
    [found remote method <7>: boolean optimize() throws java.rmi.RemoteException]
    [found remote method <8>: boolean shutdown() throws java.rmi.RemoteException]
    [found remote method <9>: boolean startp() throws java.rmi.RemoteException]
    [found remote method <10>: int transactionsSinceOptimized() throws java.rmi.RemoteException]
    [loaded /usr/local/java/jdk1.5.0_04/jre/lib/rt.jar(java/lang/RuntimeException.class) in 1 ms]
    [wrote /home/yourabi/workspace/JetEye-HEAD/main/src/java/com/jeteye/lucene/DistributedSearchFacade_Stub.java]
    [parsed /home/yourabi/workspace/JetEye-HEAD/main/src/java/com/jeteye/lucene/DistributedSearchFacade_Stub.java in 70 ms]
    /home/yourabi/workspace/JetEye-HEAD/main/src/java/com/jeteye/lucene/DistributedSearchFacade_Stub.java:4: '{' expected.
    public final class com/jeteye/lucene/DistributedSearchFacade_Stub
    ^
    [checking class com]
    /home/yourabi/workspace/JetEye-HEAD/main/src/java/com/jeteye/lucene/DistributedSearchFacade_Stub.java:4: Public class com must be defined in a file called "com.java".
    public final class com/jeteye/lucene/DistributedSearchFacade_Stub
    ^
    2 errors
    [done in 449 ms]

    [yourabi@happyending java]$ rmic -classpath
    $CLASSPATH:. -verbose -keepgenerated -nowrite
    com/jeteye/lucene/DistributedSearchFacadermic needs the class name not the file name:
    rmic -classpath $CLASSPATH:. -verbose -keepgenerated -nowrite com.jeteye.lucene.DistributedSearchFacade

  • Public class name same as file name

    Why should the public class name be same as the file name in which it is written?
    http://forum.java.sun.com/thread.jspa?threadID=198585&messageID=657978
    The above thread says it is because it makes the compilation faster. is that the only reason?
    Thank you.

    That's specified in the JLS. See � 7.6, Top Level Type Declarations.
    <i>
    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. <b>This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class
    within a package; for example, the source code for a public type
    wet.sprocket.Toad would be found in a file Toad.java in the directory wet/
    sprocket, and the corresponding object code would be found in the file
    Toad.class in the same directory.</b>
    When packages are stored in a database (�7.2.2), the host system must not
    impose such restrictions.
    </i>

  • Problem with constructors and using public classes

    Hi, I'm totally new to Java and I'm having a lot of problems with my program :(
    I have to create constructor which creates bool's array of adequate size to create a sieve of Eratosthenes (for 2 ->n).
    Then it has to create public method boolean prime(m) which returs true if the given number is prime and false if it's not prime.
    And then I have to create class with main function which chooses from the given arguments the maximum and creates for it the sieve
    (using the class which was created before) and returns if the arguments are prime or not.
    This is what I've written but of course it's messy and it doesn't work. Can anyone help with that?
    //part with a constructor
    public class ESieve {
      ESieve(int n) {
    boolean[] isPrime = new boolean[n+1];
    for (int i=2; i<=n; i++)
    isPrime=true;
    for(int i=2;i*i<n;i++){
    if(isPrime[i]){
    for(int j=i;i*j<=n;j++){
    isPrime[i*j]=false;}}}
    public static boolean Prime(int m)
    for(int i=0; i<=m; i++)
    if (isPrime[i]<2) return false;
    try
    m=Integer.parseInt(args[i]);
    catch (NumberFormatException ex)
    System.out.println(args[i] + " is not an integer");
    continue;
    if (isPrime[i]=true)
    System.out.println (isPrime[i] + " is prime");
    else
    System.out.println (isPrime[i] + " is not prime");
    //main
    public class ESieveTest{
    public static void main (String args[])
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    new ESieve(maximum);
    for(int i=0; i<args.length; i++)
    Prime(i);}

    I've made changes and now my code looks like this:
    public class ESieve {
      ESieve(int n) {
       sieve(n);
    public static boolean sieve(int n)
         boolean[] s = new boolean[n+1];
         for (int i=2; i<=n; i++)
    s=true;
    for(int i=2;i*i<n;i++){
    if(s[i]){
    for(int j=i;i*j<=n;j++){
    s[i*j]=false;}}}
    return s[n];}
    public static boolean prime(int m)
    if (m<2) return false;
    boolean x = sieve(m);
    if (x=true)
    System.out.println (m + " is prime");
    else
    System.out.println (m + " is not prime");
    return x;}
    //main
    public class ESieveTest{
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    public static void main (String[] args)
    int n; int i, j;
    for(i=0;i<=args.length;i++)
    n=Integer.parseInt(args[i]);
    int maximum=max(args[]);
    ESieve S = new ESieve(maximum);
    for(i=0; i<args.length; i++)
    S.prime(i);}
    It shows an error for main:
    {quote} ESieveTest.java:21: '.class' expected
    int maximum=max(args[]); {quote}
    Any suggestions how to fix it?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for

  • How to upload the file from website into R/3

    Dear Experts,           I want to post the data in r/3 using bdc.but flat file is available in some website for eg.'www.sap.com'.how to retrieve the flat file from the website and how to upload the data from website to r/3. It is very urgent please h

  • Scheduling Discoverer Report and distributing Discoverer Report Output

    Hi, We are using discoverer (Along with Oracle HCM R12) and would like the  END USER to schedule the reports by themselves. There is an option to schedule the report, and also an option to share it to chosen users/ responsibilities. We scheduled one

  • Time Capsule No Longer Backs Up First Computer After Adding Second Computer

    I'm new to this forum and I apologize if this has been answered elsewhere. I have a 1 TB TC. I used it to begin backups on my MacBook Pro (OS 10.5.6). I did the first backup on 1/4/09 and, up until today, it has been working very well, with hourly ba

  • Sarfari keeps crashing

    Woke up Sunday morning.  Wanted to use Safari, but when I opened it, the colour wheel kept spinning, then the program shut down.  Keeps happening.  The last app I remember downloading was for MAC CLEAN. I've searched the net, but to no avail.  I'm ev

  • Is garage band included on 10.6 OS and hdmi display issues?

    Imac, 17 inch display, 2.0 GHz, 1GB ram two issues.  Can I connect an hdmi second display (hidef tv) through the thunderbolt port and does garage band come with OS 10.6.  Can't find garage band anyplace and the second display when plugged in to an af