How to Compile a Java File with a Different Name Than the Class

Can I compile a java file with a different name than the class?

Your Java file name should always reflect the public class defined within that file. Otherwise, you will get a compiler error. For example, test.java:

public class Foo {}

Trying to compile this gives:

[steven@scstop:~]% javac test.java
test.java:1: class Foo is public, should be declared in a file named Foo.java
public class Foo {
^
1 error

So you must have your filename match your public class name, which seems to render your question moot. Either that or I don't understand what you're asking... spending some time explaining what you are actually trying to achieve would go a long way towards asking a more effective question :)

Why can't I give different name to class than the file name?

The language specification itself does not dictate this (I've just had a look, and can find no reference to it), but it's generally enforced by tools. It makes it considerably easier for tools' dependency management, since it knows where to look for class B if class A has a reference to it. The convention extends to the directory structure echoing the package structure, but again, this is just a convention.

javac allowing file name to be different than Class name in some systems

Are you certain it's still public on your friend's system? That would surprise me - if you're both compiling with javac from the Oracle JDK, I'd expect both to complain.

That said, it doesn't have to be an error. It's optional. From the JLS section 7.6:

If and only if packages are stored in a file system (§7.2), 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).

The emphasis is mine, but note that it's an optional restriction.



Related Topics



Leave a reply



Submit