Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

source file can't have more than one public class

Tags:

java

we can declare only one public file in a source file and file name must match the public class name

is there any reason to this restriction....

like image 645
saravanan Avatar asked Jan 28 '11 09:01

saravanan


2 Answers

Well, it's not a compulsory restriction in Java. It's one that the Java Language Specification mentions as an option. From section 7.6 of the JLS:

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.

But basically it's there to encourage you to make your source easier to navigate. If you know the name of a public class, it's usually pretty easy to find the source code for it.

like image 194
Jon Skeet Avatar answered Oct 31 '22 00:10

Jon Skeet


Yes, it's the specification of the Java language...

like image 23
ykatchou Avatar answered Oct 31 '22 00:10

ykatchou