This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Name of public class same as file

 
Dick Summerfield
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Small and simple question:
A public class called say, Xyz has to be in its own source file called Xyz.java.
I don't have a problem with this. It seems a logical thing to do but why is it so critical that the compiler will not allow anything else in this case? If I leave off the access modifier public (just say "class Xyz") I can call the source file anything.java. It will compile and I can run what comes out - provided I say "java Xyz ..." and forget about what I called the source.
Can anyone explain this please (or tell me where I can look)
 
Joe Ess
Bartender
Posts: 9312
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.


The Java Language Specification
 
Dick Summerfield
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Joe Ess:


The Java Language Specification

Food for thought Joe. Thanks for pointing me in the right direction
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic