Anubhav act wrote:Why only one public class is allowed in a .java file that too with the same name as of the file ??
Because it is. And I'm afraid that, unless you can find one of the designers of Java, that's the best answer you're going to get.
If you want my opinion as to why: because it's simple. That has always been Java's general philosophy.
Right now the compiler only has to look for one file per package, and all files in the same package. That's a lot faster.
If you search this forum, you will find lots of other answers to the same question. Some of them might be helpful to you.
Java introduced the rule that there can be only one class per java file, the folder structure of the source folder matched the package name exactly, and each java file compiles into couple of classes because it made sense for the IDEs at the time. When you opened a class, all the IDE had to do is use the package name to traverse the folder structure to find the file. When you changed the file, all it had to do is compile these one file into a class file without requiring an additional link step. This rediced the size of the compiler too.. because all the compiler has to do is load this one file and it's dependencies to compile the class. It doesn't need to load everything into memory. This led to more memory being available to the Editor.
Hmm now that I think about it, having a well defined rule for how source files are stored, lead to the copiler becoming lightweight, which lead to the IDEs having more features, which includes being able to keep track of where all the classes are stored, which lead to people asking "Why do we need a rule for how source files are stored?"
Stephan van Hulst wrote:
Jayesh A Lalwani wrote:Java introduced the rule that there can be only one public or protected class per java file
Ummm, I guess that's what Stephan wrote, not what Jayesh wrote. Stephan, can you show an example what you mean by "or protected" there? I don't think it's correct, unless you're talking about member classes, in which case private is also an option, and there's no limit on the number. Perhaps you meant there can only be one public top-level class? And any number of top-level package-protected classes?