Why only one public class in a source file?

why we have to write only one public class in a source file?

PhHein wrote:
Because the JLS says so.It does?
From section 7.6 of the JLS (third edition):
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.
>
To my mind, it's strongly recommending, rather than mandating, this practice. All academic of course, merely shifting the answer from "Because the JLS says so" to "Because pretty much all Java compilers say so". I don't know of any that don't enforce this, but of course, that doesn't mean they don't exist

Similar Messages

  • Why only one public class in one file

    why does java allows only one public class in one file?
    Why can not we have two or more public classes in file?
    Thank u.

    Note, you can have multiple inner classes.
    e.g.
    public class A {
        public static class B {   }
        public class C {   }
        private class D {   }
    }

  • Why we can have only one public class in one source file

    why we can have only one public class in one source file

    When the java compiler is run it looks for classes referenced by the classes you are directly compiling. When looking for these referenced classes it looks for source as well as class files and compiles them automatically if the coresponding class files are missing, or older than the source.
    In order to do this it must be able to work out the source file name for any given class which might be referenced from another (the rule also applies to package level access).

  • 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.

  • Only one public class - why???

    Hi
    I have come across this statement many places -
    "There can be only one Top-Level 'public' class in
    a java source file which should have same name as that
    of the fore mentioned class."
    I know that the compiler searches for the class
    with same name as that of the file that is passed to
    the compiler.I am also aware that a Java source compiles
    smoothly with One or None Top-Level 'public' class,
    but I fail to comprehend this -
    Why can there be only one TOP-LEVEL 'public' class
    in a Java Source file?
    The importance of 'TOP-LEVEL' is as important as
    any thing else, as you yourself check that a Nested
    class within an Enclosing class can be 'public' along
    with someother Top-Level 'public' class in the program
    compiles smoothly unlike having TWO Top-Level 'public'
    classes in same file.
    I have found no reason supporting this statement in any
    of the refernces I have checked out.Ppl I have asked told
    me that it is so coz Java Spec say so.
    Is there an better answer to my question?
    Thanx in advance, appretiate it.
    Regards
    Pradeepto

    I have found no reason supporting this statement in
    in any
    of the refernces I have checked out.Ppl I have asked
    told
    me that it is so coz Java Spec say so.I can tell you that anybody who says its because the Java spec says so, is wrong - the Java spec does not say so.
    It is a limitation of Sun's javac compiler, which many other compilers exhibit as well. I don't know the full formal reasoning behind it (and would be interested in knowing if you find a good answer), but I assume it simply has to do with finding classes without having to load everything on your classpath.
    Whether other compilers are purposely acting the same way as javac, or whether it is some sort of performance optimisation that most vendors feel is worthwhile, I couldn't say.
    I don't see what you're saying about top-level and nested classes. Although you can declare a public nested class inside a non-public top-level class, the nested class is not actually publicly visible, by virue of its enclosing class not being publicly visible.

  • Why can we have only one public class in our program

    Why is it that we can specify only one class as public in our source code .................................................
    Once i'd put one inner class as public ...which means now i have 2 public classes ..............out of which one is the inner class...what is the use of such public class which can be accessed by only its outer class.........
    plz. help

    Once i'd put one inner class as public ...which means
    now i have 2 public classes ..............out of
    which one is the inner class...what is the use of
    such public class which can be accessed by only its
    outer class.........
    plz. helpWrong.
    Public inner class can certainly be accessed outside.
    You just have to preface it with the name of the outer class.
    A.java
    =====
    public class A {
       AA example = new AA();
       public class AA {
           public int value() { return 5; }
    }B.java
    =====
    public class B {
       public static void main(String[] args) {
          A x = new A ();
          A.AA y = x.example;
          System.out.println(y.value());
    }

  • Public class and the source filename

    May be I'm asking a silly question, but why the name of the source file needs to match with the public class's name?
    If the rule is that only one public class is allowed per source file, then the compiler can simply flag the error and quit.
    Any reasons behind this, other than for the ease of compilation?

    I refer you to the Java Language Spec:
    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.

  • Why only one client ???

    Why only one client is possible for one server in case of BW ?? And why it is not the case in R/3???

    Hi,
    have a look at sap help:
    Clients in BW:
    http://help.sap.com/saphelp_nw04/helpdata/en/b7/8a9a3aaf894871e10000000a114084/content.htm
    Assign points if its helpful.

  • 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>

  • Can we define two public classes in a same file?

    Is it possible to define two public classes in a same file
    Thanks a lot
    So jag

    Do you realize RMI too, what caused this please!
    loading chat.rmi.RMIServer.class for debugging...
    chat.rmi.RMIServer.class successfully loaded
    java.rmi.StubNotFoundException: Stub class not found: chat.rmi.RMIServer$RemoteLogonManager_Stub; nested exception is:
    java.lang.ClassNotFoundException: chat.rmi.RMIServer$RemoteLogonManager_Stub
    java.lang.ClassNotFoundException: chat.rmi.RMIServer$RemoteLogonManager_Stub
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:191)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:296)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:253)
    at sun.rmi.server.RemoteProxy.loadClassFromClass(RemoteProxy.java:198)
    at sun.rmi.server.RemoteProxy.getStub(RemoteProxy.java:100)
    at sun.rmi.server.RemoteProxy.getStub(RemoteProxy.java:62)
    at sun.rmi.server.UnicastServerRef.setSkeleton(UnicastServerRef.java:155)
    at sun.rmi.server.UnicastServerRef.exportObject(UnicastServerRef.java:115)
    at sun.rmi.server.UnicastServerRef.exportObject(UnicastServerRef.java:102)
    at java.rmi.server.UnicastRemoteObject.exportObject(UnicastRemoteObject.java:276)
    at java.rmi.server.UnicastRemoteObject.exportObject(UnicastRemoteObject.java:180)
    at java.rmi.server.UnicastRemoteObject.<init>(UnicastRemoteObject.java:80)
    at java.rmi.server.UnicastRemoteObject.<init>(UnicastRemoteObject.java:67)
    at chat.rmi.RMIServer$RemoteLogonManager.<init>(RMIServer.java:23)
    at chat.rmi.RMIServer.<init>(RMIServer.java:16)
    at chat.rmi.RMIServer.main(RMIServer.java:11)
    at symantec.tools.debug.Agent.runMain(Native Method)
    at symantec.tools.debug.MainThread.run(Unknown Source)
    The communications channel closed.

  • If you have two public class in a java file what will be the error ?

    Q:If you have two public class in a java file what will be the error and how will you remove that.?

    Kannan_S wrote:
    I dont want you to be on that list . Here goes my explanation..
    A class is well defined with members and functions
    An abstract class is not defined well as compared to a full fledged class (talking more generically)
    An interface is more abstract.
    I was asking the author who has posted this question to be like a class(very clear)
    and not either as an abstract class or an interface
    Hope i have made it clear..Not in the slightest. This has absolutely no bearing whatsoever on the question asked. Not to mention that classes are classes, and all equal in the eyes of the compiler, be they abstract, concrete or interfaces. It's difficult to see what your point is, to be honest, but I suspect it wouldn't be worth seeing anyway

  • Can you place more than one class in a source file?

    If so how is this done because I get the following error when I try to.
    IPHunter.java:100: class Arguments is public, should be declared in a file named Arguments.java
    public class Arguments {
    Thanks in advance

    When having two classes in the same file, only one should be public, and the file should be named with the name of that class.
    Try removing public from the class Arguments, and if you have to use it from classes outside the file, you should have a file Arguments.java
    Hope that helps,
    Al

  • Why only one channel of sound in sequences?  Please someone try this quest

    When I add a sequence to a sequence, I have only one channel of sound but, when I open that sequence I have 2 channels of sound.
    Is it a sequence setting and if it is I see:
    outputs 2
    downmix 0
    grouping: Stereo selected
    Dual mono not selected.
    I swith these around a bit but get no change.
    My raw footage say "2 Mono" from my Sony DSR PD-150 at 16 bit, 48 khz.
    I usuall use one channel for camera sound and 2nd channel for mic.

    the number of audio channels that your nested sequence will contain is the same as the number of audio outputs you have selected for that sequence ...
    for example, if you create a sequence with 10 tracks of audio, but have only set the sequence to have 2 audio outputs, then when you nest that sequence the nest will have only 2 tracks of audio ... change the audio outputs to 4, or 6, or 8, or 10 etc regardless of how many tracks you actually use, and the sequence, when nested, will have the same number of audio tracks as the sequence has audio outputs
    ... ok, so that explains the relationship between audio outputs and the number of tracks of audio that a nested sequence contains
    so why are you getting only one channel of sound when you edit it in to another sequence? my guess is that you are only patching 1 channel ... load the source sequence into the viewer (drag and drop), now check in the patch bay area at the left of the timeline window to make sure that your a1 to A1 and a2 to A2 connections are not broken ... and edit it in.
    cheers
    Andy

  • Why only one recent backup to restore from?

    I backup up my iPhone every day. In iTunes>Preferences>Devices, why do I only see today's backup and a backup from three months ago?

    Only one backup is kept by itunes(this backup is overwritten each time you sync), except for restore backups, which are not overwritten & are kept by time & date stamp. The reason you don't see any other backups listed is because you most likely have never restored your phone. If you performed a sync before you restored from backup, your backup was overwritten & that's why your info was not replaced.
    If you backup your computer, you can extract your backup from that computer backup, replace the one on your computer with this & restore from that backup. DO NOT SYNC before restoring from this backup. You will be given the option to create a backup before you restore, decline.

  • Why only one leading ledger?

    Hi
    I am aware that in new GL you can have only one leading ledger. you can have as many non leading ledgers. Only leading ledger values flows to CO.
    what can be the possible reasons for the restriction of "only one leading ledger"???
    thank you in advance
    Regards
    Vedavatee

    Dear expert
        In New G/L, there is one leading ledger for each client that is valid for all company codes
        You can define only one ledger as the leading ledger u2013 SAP provides the leading ledger u201C0Lu201D
        The leading ledger is integrated with all subsidiary ledgers
        Only the values from the leading ledger are sent to CO
        The leading area in Asset Accounting (depreciation area 01) must be posted to the leading ledger
        Leading ledger uses the (additional) local currencies assigned to the company code
        Leading ledger uses the GL Total Table: FAGLFLEXT
    In each company code, the settings made for the following parameters are automatically applied to the leading ledger:
        Currencies
        Fiscal Year Variant
        Posting Period Variant
    Regards
      Ajeesh.s

Maybe you are looking for

  • Version of developer 6i  in 11.5.10.2

    hi....! How to know the version of developer 6i in 11.5.10.2? regards vijay

  • I need help trying to print ,move and resize multiple images on a page to print!help!

    can anyone give me to some advice. I was using an older version of photoshop elements where i could position the image i wanted to print on the page. I could resize it, move it around and add more photo's. I print small images that I cut out for jewe

  • Using of CONVERT DATE

    Hello, I have two questions relating to a part of a source code, which I have to analyze:   CONVERT DATE INTAB-DATUM INTO INVERTED-DATE DAT_INV.   SELECT SINGLE * FROM TCURR WHERE KURST = INTAB-KURST AND                                              F

  • Airport fails to reconnect

    the wireless airport fails to reconnect after awaking from sleep or rebooting.. i get the error message that says "this computer's internet connection appears to be offline." i have 10.4.6 and firmware update

  • Audition CS5.5 licensing

    Hi May I install my Audition CS5.5 on two PC's, f.ex. workstation and laptop? Thanks. /Ulf