开发者

Why java doesn't allow two top-level class per file? [duplicate]

This question already has answers here: Closed 11 years ago.

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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜