-3

Possible Duplicate:
Why only 1 public class in Java file

public class Sample {

}

public class Sample2 {

}

why java doesn't allow this?
and why we must give the file name same as class name?

Community
  • 1
  • 1
Chakravyooh
  • 117
  • 7
  • Duplicate of these questions. http://stackoverflow.com/questions/3578490/why-only-1-public-class-in-java-file and http://stackoverflow.com/questions/2134784/why-filename-in-java-should-be-same-as-class-name – shinynewbike Sep 13 '11 at 10:29
  • But it does; its only `public` top-level classes that must be declared in their own files. – meriton Sep 13 '11 at 10:34

3 Answers3

0

Well, I do not know of any documented reasoning, but it is not difficult to see that this links the file system with the class structure.

This makes easier (both for programmers and for compilers/IDEs) locate the classes they are looking for, when needed.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
0

Well, not a technical reason, but it's good practice; enforcing that might be a little inconvenient at times, but ultimately it benefits the programmer.

However, it's easier to locate the code for a class if it just needs to look for a file with the same name, rather than having to search through all available code files.

Flynn1179
  • 11,925
  • 6
  • 38
  • 74
0

Java won't allow two top-level class per file for the same reason that the class name must be equal to the filename.

When setting the classpath, the Java Virtual Machine will look for the class that has the name myclass.jar (or .class, when compiled). If you put two classes in the same file, one of both won't be accessible.

For that reason, also, a class cannot extend more than one file.

Roberto Luis Bisbé
  • 2,080
  • 1
  • 15
  • 22