Package, public class and files...

It has always surprised me that Java compiler allows a class to be called public only if it is placed in a separate file with the same name "Name.java". Personally I often place classes in the same file, one after another, and enjoy the compactness of the solution: one set of imports for all:
// file Mumbo.java
package some.path.creole;
import import_one;
import import_seven;
import import_heaven;
class Mumbo
class Jumbo extends Mumbo
class Jambolaya extends Jumbo
public Jumbo serve_plate_mild() {}
public Jumbo serve_plate_spicy() {}
}and this works beautifully, as long Mumbo, Jumbo and Jambolaya are being used in the same package "creole," but one to stay in the Bayou. Java compiler would not allow to denote Jumbo or Jambolaya as public.
This drives me "nuts", I am reading through Arnold, Gosling, Holmes to find the detail in the language specification just why is that so?
What is the benefit or the reason for such a limitation? I can split these classes into separate file, sure, its the cut-and-paste works on "import seven..import_heaven" over and over again (maintenance issue! the "Repeat thyself" syndrome) and that's it.
Could some of the language gurus tell me, why can't I have Jambolaya in Florida? (Actually on occasion I take me the liberty to consider myself a language guru, but here I must submit to a defeat... I cannot find a rational reason for this design decision!)

ThomasH_usually wrote:
Oh I do have "475 classes in same file," what helps+ me brilliantly to find them quickly, and to maintain them easier... For example in a non-trivial project I might like to edit on several classes at the time, new Mumbo, new Jumbo detail. Why would that be "not scalable?" And I do want to compile them all in a bundle, never separate, what the single file provides for me. So you see, as always "your mileage may vary", I would not attempt to impose on your preference to keep "475 separate files" and call it "better." I do not have that need, suit yourself, be happy.
Good for you. Not so good for other developers on your team or others that follow you later. Merging with multiple developers would be a real joy as well.
Simple solution. Write a trivial parser that breaks your file into the correct pieces. Add that to your build.
I see so far only personal opinions, but no justification in language specification (or standard) itself. I can assure you that the language does require it. So what you are in fact asking for is what the personal opinion of the authors was that drove them to this.
I can note that having worked with many languages, with many developers, read many books and many magazine articles I have never seen anyone advocate for your personal preference. Thus my personal opinion is that many people do not like it. Including the authors of java. Thus it is not allowed.
The point here is that aside of package vs. public visibility, all classes in one file or in separate files, will lead to the same set of *.class files and even to the same bytecode. Only that "my way" I have 1 set of imports, you have "475 sets," on which you have to edit, should you be forced to add a new import. I am sorry, I fail to see the benefit in that.Which is a pointless and meaningless rationalization. You might as well just insist that it import everything available to it because on a large project your import list is going to be close to that.
Conversely with separate files I can know exactly what dependencies that class has.

Similar Messages

  • How to create Package( development class) and how to assign the program

    Hi,
    Can any body give me the steps to create the package (developement class) and also please give me the steps to assign the local object ( program) to that development class.
    thanks in advance
    KP

    Hi,
       This document will help you to create package and move local package name to your package.
    Package  Creation:
    1.T-code=SE80.
    2. give the option 'PACKAGE' in text field, give 'PACKAGE NAME' then enter.
    3. The next screen will open in that screen you shoul give short text and Software Component-'HOME'.  then enter.
    4. Next screen will open here you should give create request then next page will open
    5.In the next page give short description this is your package identification,then click 'SAVE ' button now one  unique number will open then give 'YES' button, now your package is created.
    HOW TO MOVE LOCAL PACKAGE DATA TO YOUR PACKAGE
    1.IN  the same screen you should give program option, then open your local program ,
    2.'WRITE  CLICK YOUR PROGRAM NAME', then give 'COPY' option
    3.Next window will open here you should give 'TARGET PROGRAM NAME'.
    4. THEN you should give you 'PACKAGE NAME'.
    now you can store local package program's to your package.
    IF HELPFULL GIVE REWARD POINTS

  • Public class and just class ??

    when i try to compile this program i get an error message
    /* Well, maybe this isn't completely useless. */
    /* This program uses API introduced in 1.1. */
    public class Useless {
    public static void main(String[] args) {
    System.out.println(java.util.Locale.getDefault());
    the error message is this :
    Public class Useless must be defined in a file called "Useless.java".
    ut when i take out the public and just leave it as
    class Useless {
    it works
    why is that ???
    any info would be greatfully recieved
    thanxs
    Anthony

    If you declare a class as public, it must be the same name as your filename, you are going to open the class to public for every purpose. But you can only have 1 public class in every file.
    If you declare a class without a public keyword, you can have as many classes of that type you want inside your class, its not gonna link up with the filename and it will not be open to public, in this sense, it is not visible to other classes which are not in the same package.

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

  • Q: How to setting the Sun ONE Studio JDK and Class(and file) Path.

    1.I'll use two JDK version.
    2.I'll add the Oracle JDBC driver.
    3.In my city, I'm didn't find the Sun ONE Studio book.(Forte for Java 4).
    need help.
    Thank you.

    Dear javaunter20000,
    I'm used the Windows XP Professional(SP1),
    I'm use the
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    String url="jdbc:oracle:thin:@127.0.0.1:1521:netcob";
    String user="***"; String password="***";
    Connection conn= DriverManager.getConnection(url,user,password);
    connect Orcale, compiler return:
    ***[34:1] unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    ^
    ***[34:1] unreported exception java.lang.InstantiationException; must be caught or declared to be thrown
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    ^

  • Question about access non-public class from other package.

    Hi, everyone!
    Suppose class A and class B are in the same java file of package pkg1
    -- A.java. So, A is a public class and B is a non-public class.
    If I want to access class B from another class class C and class
    C is in package pkg2. When compiling, an error occurs indicating
    that class B is not visible to class C.
    So, If I defined serveral classes in one java file and I want to
    access every class from other package. How should I do?
    (I think in one java file, there should be only one public class and
    only the public class can be accessed from other package.)
    Thanks in advance,
    George

    So, If I defined serveral classes in one java file and
    I want to
    access every class from other package. How should I
    do? As you already seem to know, there is at most one public class allowed per source file (at least, with javac and most popular compilers). So if you want more than one public class, you will need to use more than one file...

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

  • Breaking Down Classes Into Files

    I'd like to know what's considered best practice when dividing multiple classes into seperate files. I know you can have only one public class per file, and I've heard some people say it's best to have one class per file, period. But the one-class-per-file rule seems overly strict.
    To give a specific example, I have a class which manages event handlers and event generators. The class receives events and delegates them to one of its registered handlers. The handlers can, in turn, spawn new events by calling the event generators, which have package access.
    Currently, I have the handlers, the generators, and the public class which manages them all in one file, which I know is not good, especially since some of the handlers and some of the generators are fairly large classes in their own right. However, it would be silly (I think) to put every handler and every generator in its file, because some of them are almost trivially small, and none of them have public access. But what is the best way to break them down: Should I put the handlers all in one file, and the generators all in one file, giving me three files total? Or are there other principles that should guide me?
    Thanks for any thoughts,
    John

    That's a good point. Although, as you said, it
    doesn't really apply in my case. That is, if I put
    all the handlers in a file called EventHandlers.java,
    that should be pretty clear for me. And, in fact, it
    would probably be easier to work with the classes if
    they are all in one file.But what do you think about when I say reuse? Don't you think that one class per file will make it easier to reuse the classes? As it is now you have to take them all. Since you have things that are in common for them I would say that you must have interfaces, and abstract classes. Couldn't they be reused in another project? So there are benefits even in small projects. It's also better to have many files if there are several developers and your version manager doesn't allow multiple checkouts of the same file.
    >
    Also, you mentioned sub-packages. I'm assuming
    classes in sub-packages do not have access to their
    parent's package-access members. What I really would
    like is to prevent any classes except the event
    handlers from accessing my EventManager's generator
    members. Could you solve that problem in another way? Why do they need access to the EventManager?
    Are you saying I should put all the other
    classes in a sub-package? I say that you should put related classes in sub-packages. Look at the package structure of the java core (can be seen in the javadoc)
    /Kaj

  • Why do we need public classes?

    I read that a public class is more visible than a default (non-public) class as the latter is merely "package-visible". However, it appears that even if a class (c in package p) is not declared to be public, it can still be accessed by:
    1) p.c
    2) import p.c
    So what is the use of declaring a class to be public? Why can't we just write:
    class c {...}
    every time for every class without the modifier public.
    Can someone show me an example that illustrates the difference between a public class and a default class?

    I read that a public class is more visible than a
    default (non-public) class as the latter is merely
    "package-visible". However, it appears that even if a
    class (c in package p) is not declared to be public,
    it can still be accessed by:
    1) p.c
    2) import p.c
    How does that appear so?
    Trying to do it the compiler says that "p.c is not public in p; cannot be accessed from outside package" and does not generate a class file.

  • What is the relation between main class and inner classes

    hi
    i want to make a UML design and o want to know how to draw the relation betwwen the main public class and inner classes?
    and what is the relation?

    BaffyOfDaffyA wrote:
    Please keep in mind that if you spell better you will get better answers and if you add duke stars you will get better answers and if you mark the thread as a question you will get better answers. That will make it look like you are paying attention and that you really want an answer.
    My best answer based on your rather vague question:
    A minimal public class in a file named "Minimal.java" in the directory named "minimal":
    package minimal;
    public class Minimal {
    private int variable;
    public Minimal(int var) {
    variable = var;
    public int getVariable() {
    return variable;
    }This would be an example of adding an inner class:
    package minimal;
    public class Minimal {
    private int variable;
    public Minimal(int var) {
    variable = var;
    public int getVariable() {
    return variable;
    public class Inner {
    private int innerVariable;
    public Inner(int var) {
    innerVariable = var;
    public int getInnerVariable() {
    return innerVariable;
    }The inner class is exactly like any other inner class except if you are accessing it from anything else other than Minimal then you would have to add Minimal. right before Inner for example, where the Minimal class could use
    Inner inner = new Inner(5);other classes would have to use
    Minimal.Inner inner = new Minimal.Inner(5);
    See [Inner Class Example|http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html] or [Nested Classes|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html] for more information.
    He is probably not asking what an inner class is or how to declare one in raw source code. To me he is asking how do I
    explain this relationship in a UML diagram and as UML is not and exact science and expression can vary a lot
    between UML design applications I didn't want to stab in the dark.
    @OP I would say whatever seems most logical to you and your team, write something that reads.

  • Public class

    Hi,
    I want to know why the name of a public class and the name of the file containing the class should have the same name.

    It makes maintenance and debugging easier. Might make class loading easier and/or more efficient also.

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

  • Character Encoding and File Encoding issue

    Hi,
    I have a file which has a data encoded using default locale.
    I start jvm in same default locale and try to red the file.
    I took 2 approaches :
    1. Read the file using InputStreamReader() without specifying the encoding, so that default one based on locale will be picked up.
    -- This apprach worked fine.
    -- I also printed system property "file.encoding" which matched with current locales encoding (on unix cooand to get this is "locale charmap").
    2. In this approach, I read the file using InputStream as an array of raw bytes, and passed it to String contructor to convert bytes to String.
    -- The String contained garbled data, meaning encoding failed.
    I tried printing encoding used by JVM using internal class, and "file.encoding" property as well.
    These 2 values do not match, there is weird difference.
    For e.g. for locale ja_JP.eucjp on linux box :
    byte-character uses EUC_JP_LINUX encoding
    file.encoding system property is EUC-JP-LINUX
    To get byte to character encoding, I used following methods (sun.io.*):
    ByteToCharConverter btc = ByteToCharConverter.getDefault();
    System.out.println("BTC uses " + btc.getCharacterEncoding());
    Do you have any idea why is it failing ?
    My understanding was, file encoding and character encoding should always be same by default.
    But, because of this behaviour, I am little perplexed.

    But there's no character encoding set for this operation:baos.write("���".getBytes());

  • Why a public class name and file name same?

    All of us know that, a public class should be declared in a file which has the same name of that class. What is the underlying concept behind this..Can someone give a clear explanation?
    Thanx..
    Sandeep Joseph
    Paragon Solutions
    [email protected]

    Another issue, it was said that the file must be named
    after the class to find the class's code when
    compiling dependent classes. Doesn't this apply to
    non-public classes too (with the dependent class being
    located in the same package)?This applies to all top-level classes ...
    You can define multiple classes in one file though:
    class A {
    class B {
    }It's perfectly valid to have both classes defined in the same file (named A.java if A is the first class to be defined in that file).
    You will get a compiler warning as soon as you reference a non-top-level class from a class that is defined in another file, though.

  • Want to package a class file and a jar file in main jar file

    hello folks,
    i have a class named launch.class
    and a jar file named First_Sample2.jar
    First_Sample2 is an application that i have made which requires more memory than is generally allocated by the JRE. so, launch.java file just contains code to execute the command:
    javaw -Xms128M -Xmx256M -jar " + path + "First_Sample2.jar"
    where path variable refers to a directory which contains First_Sample2.jar
    problem is that the only way i can use this code is by keeping two separate JAR files, one is launch.jar, the other is First_Sample2.jar and then execute launch.jar, which will in turn call First_Sample2.jar (which means I have to provide anyone with 2 separate files if they want to use my application)
    is there any way in which i can combine both these jar files into one?

    Well there is a couple ways you can achieve this, but I am telling you that packaging a JAR within a JAR will not work because classes within the internal JAR will not be recognized on the classpath.
    The easiest way to get the user to run your program with a simple double click would be to hide the two JAR files from them completely, having them reside in a folder somewhere on the user's computer. I would use a batch file (Windows environment) or an .sh file (Unix) that would set up your classpath variable and then call java to execute the main class in your main JAR.
    For instance:
    cd [Where java.exe resides]
    set CLASSPATH=[semi-colon delimited absolute file paths pointing to your two JAR files and any other JAR files that they reference]
    java -cp %CLASSPATH% [main class]
    The user would have access to this batch file, perhaps on their desktop, where they can double click to execute teh program just as if it were an EXE file. This is the best way because it hides the JAR files from the user.
    If you would like to combine the two JAR files however, you would need to extract the contents of the secondary JAR file and then include them in with the contents of the main JAR file. That is the only other way that all classes are visible on the classpath.

Maybe you are looking for

  • Problems with email, Macbook Pro, Yosemite

    Keep getting knocked out of email. Different errors, mostly cannot connect to server. Per Apple's mail support page. One of the settings should be Password. When I change to password in settings, it keeps switching to MD5 Challenge -Response. Could t

  • System Master Data Process Chain

    Hello Guys, I am working on Admin cockpit. So far it s going well. However, I am struglling with scheduling System Master Data Process chain. When I look at its logs, I see that Operation Type (WHM)- Texts becomes red and Attribute Change Run (final

  • Trouble installing photoshop 7.0 and illustrator 10

    I've been trying to install a couple of Adobe programs out of the creative suite, but the "classic environment" isn't detected, so the programs keeps getting kicked out.

  • Reg Oracle Apps DBA Certification

    Hi, I am Certified for DBA on both 9i and 10g. Now I am planning to do Oracle Apps DBA Certification. Is that necessary I need to the Database Funda I and Funda II Exam again. Is that 11i Exam is alone is enough to be Oracle Apps DBA? Pls Clarify me.

  • How can I transfer my itunes from an old computer to my new one?

    I'm trying to get my itunes off of a gate way to my Sony Vaio E- series. how can I go about doing this?