In Java, the name of the file should be the same as the name of the public class
contained in that file. Why is this a limitation? What purpose does it serve?

- 7,942
- 7
- 60
- 65

- 5,291
- 13
- 43
- 47
-
32This question should be rephrased: Why would any language deliberately make it more difficult to find your source for absolutely no benefit by allowing arbitrary file/class naming mismatches? – Bill K Jan 25 '10 at 19:06
-
Related: https://stackoverflow.com/questions/13811020/error-class-x-is-public-should-be-declared-in-a-file-named-x-java – starball Apr 23 '23 at 22:48
7 Answers
Java had an interesting approach: where giving a programmer a choice can only degrade the programming experience, remove the choice.
They did this in quite a few places. Filenames and packages for sure, but also not allowing multiple public classes in a file (never good), not allowing you to split classes between files (Damn hard to work with!), etc.
Languages make a lot of decisions like this, they all affect usability and maintainability. Some others that might have been good choices:
Public variables: I've never needed one, nor have I ever seen a situation where some smart programmer thought one was needed and was actually right.
Method/class size limitations would be great, but this could get sketchy (it could easily be implemented by code checkers, the problem is typically that the companies that need the most help are the ones that don't know they need help and, therefore, don't use tools like code checkers).
The point of the answer is that although isn't stuff that matters to most small teams, when your team grows and has multiple sites with split teams and consultants throughout the world, You really to appreciate the inflexibility.
In response to setters/getters comment:
Java beans were an abomination created by Borland to hack their GUI up, then retrofitted into Java.
Horrid idea--a distraction from OO programming--Getters and setters A) show too much of your implementation and B) make you think in terms of operating on data from another object rather than asking the other object to execute an operation for you. Bad hack for people who can't yet think in OO.
Getters are needed occasionally but shouldn't be added unless seen to be absolutely unavoidable.
Setters should be avoided at all costs. If you absolutely need to externally modify the state after an object is constructed, try to use the builder pattern and protect your setters from being called after any operation has been executed.
There are obviously exceptions to everything, and many "Getters" are actually critical object business logic, like String.length() which would be required no matter how String was implemented and isn't even implemented by just returning a property--a great case for a "Getter" if you even want to call it that.

- 62,186
- 18
- 105
- 157
-
3The getX/setX paradigm was not established yet when Java was designed.I believe this to be the result of JavaBeans having to code to interfaces, and you cannot have public variables in an interface. – Thorbjørn Ravn Andersen Jan 25 '10 at 19:42
-
-
There actually are class and method size limitations, they're just so big that you don't run in to them in practice. – Antimony Jun 28 '13 at 04:59
-
Public variables can be useful where the class is in fact a gloriried struct and would just have public (and pointless) getters and setters – Richard Tingle Jul 14 '13 at 10:14
-
Although in practice you are exactly right, it's really useful occasionally, in theory that would be terrible OO and shouldn't be done. I've done it that way a few times but only as a hack and usually end up tearing that out later. So really the fact that you can have public variables only hurts your code and I guess I stick with my statement that they shouldn't exist. A class with just setters and getters OR a class with public variables is a really terrible pattern. – Bill K Jul 16 '13 at 06:10
-
Yeah, even when I'm forced to use a kind of data object (e.g. you're dealing with an obtuse JSON parser and it wants to convert everything to an object), I will still avoid setters and either use builders or push everything through the constructor. – Hakanai Sep 13 '13 at 03:55
-
Just some catchup on comments I never replied to. @ThorbjørnRavnAndersen I believe Set/Get was a pattern to allow Borland to use objects generically in their builder. You just create a new object with the properly named methods an borland could reflectively analyze it and display properties to the user to edit. Database programmers started using it the same way.. These days you'd do that kind of thing with annotations. It was simply a way to get rid of the (often xml) meta-data that was needed for other languages like C++ – Bill K Apr 17 '14 at 17:50
-
@helpmethod an anology to my comment about companies in my answer--I believe it's the programmers that don't think they need "Restrictions" that need them the most, but then in the past 4 years since I posted that answer I've come to fully believe that no one language is good for every problem and often programmers that want something more flexible just might not be facing the same problems I am (Team-interaction, long-term code maintenance, etc). – Bill K Apr 17 '14 at 17:53
-
@BillK What exactly are you implying when you explicitly mention Indian and Chinese consultants as a reason for appreciating the inflexibility? This is probably the most bizarre thing I've read on SO in a while. – Chetan Kinger Feb 22 '18 at 15:04
-
My experience with offsite consultants was that it was extremely hard to maintain a set of coding practices that would work well for all involved. The more flexibility you have in code, the more likely an off-site team is to create something--well in my experience something truly bizarre. The language/communication problem multiplied this. When a group is co-located they can more easily learn what coding patters are easiest for the rest of the team to consume. In the meantime, a language without complicated bells and whistles makes extremely difficult/bizarre code less likely. – Bill K Feb 22 '18 at 16:53
I was about to say, that it is simply a must. But I looked at the JLS, and it is not that strict. From the JLS's perspective, it is left to the compiler to choose whether to set such a restriction or not.
Practically spoken - common compilers do have that restriction, and, as other already explained, it's much easier for the compiler to find a compilation unit or for a classloader to find a class file with such a restriction in place.

- 113,398
- 19
- 180
- 268
-
8As far as the language spec is concerned, source code doesn't even need to be contained in files. It is a convention for compilers handling source code in files. – Tom Hawtin - tackline Jan 25 '10 at 19:27
To be more specific, the filename should have the same name as the public class name in that file, which is the way to tell the JVM that this is what the entry point is for you.
-
Actually the entry point is specified in the jar manifest. It has nothing to do with the arrangement of source files at the Java level. – Antimony Jun 28 '13 at 05:02
-
@Antimony, this is if you have to run the single java file. And even th entry point you mention in the Manifest should have the same naming convention. – GuruKulki Jun 28 '13 at 08:56
-
1It has nothing to do with the entry point. You can create a non-`public` class called `Foo` in a file called `Bar.java`, compile it, and run it via `java Foo`. The `java` tool doesn't care whether the class is `public`, and determines the entry point by the class name you gave it, not the name of the source file (which isn't even in the class bytecode if you turn off debug information). Other startups (running a jar, servlets) equally determine the entry point in other ways, not by the source filename. – T.J. Crowder Jul 06 '18 at 11:40
It is just the convention set by Sun, the makers of Java.
The purpose is organization; the reason is so that everyone who codes in Java will have a consistant way of naming files.

- 84,206
- 33
- 197
- 283
-
I downvoted this answer because it is incorrect. My edit simply corrected this answer. You decided to roll it back. It's your business now. – nbro Oct 09 '18 at 18:29
-
@nbro: This answer is 100% correct. Your edit literally said the same thing in different words, while removing the useful link _(which was dead but is now fixed)_. phisch's comment is also superfluous, because he's arguing the same point I already made. – BlueRaja - Danny Pflughoeft Oct 09 '18 at 18:32
-
@BlueRaja-DannyPflughoeft This answer is not 100% correct and therefore it is incorrect. "the reason is so that everyone who codes in Java will have a consistant way of naming files.". This is not the only reason, therefore your answer is incorrect or, in nice terms, misleading and incomplete. – nbro Oct 09 '18 at 19:00
Each public class must be in a file where the FileName matches the ClassName and a package where the Packagename represents the Directory structure, written in the dotted-form (slashes become dots, like com/example/app becomes com.example.app).
This convention is not random. The compiler has to be able to find the source files and the class loader has to be able to find the implementation. Matching package names and classnames makes this really simple and, more important, fast.
This convention does not apply to non-public classes. This is because non-public classes have a very limited visibility and can only be used within the package where they are defined. Thus, in both cases, the compiler and the runtime environment have already located the correct files.

- 4,571
- 2
- 34
- 52
-
Non-public, default access ("package private") classes can be used anywhere within the same package. – Tom Hawtin - tackline Jan 25 '10 at 19:28
-
Yes, that was actually a typo. They can be used within the package, but nowhere else. Private classes can only be used within the file they where defined – phisch Jan 25 '10 at 19:40
It is useful in locating the class. i.e. Suppose different file names are allowed and if you have created an instance of a class then the compiler has to search the class in all file instead if the file-names are same as that of the class the performance of locating and using the class is increased. Their might be other reasons too.

- 11,938
- 19
- 92
- 127
As long as it is not public a class can have a name different from its file name. The class can also have main method. Class file will be generated with the class name but not with the source file name. The class name should be used to execute it.
Reason is: default class is package private, thus javac doesn't have to find this source file of this to compiler some other java program from outside of package.

- 1,019
- 7
- 7