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
How to Display Legend for Pie Chart in Columns
How to Override and Overload Static Methods in Java
Coding Conventions - Naming Enums
Java:Why Should We Use Bigdecimal Instead of Double in the Real World
Java Comparator Class to Sort Arrays
How to Keep a Scanner from Throwing Exceptions When the Wrong Type Is Entered
Print "Hello World" Every X Seconds
Convert Escaped Unicode Character Back to Actual Character
Maven Compile with Multiple Src Directories
Differencebetween 'Java', 'Javaw', and 'Javaws'
File Upload with Java (With Progress Bar)
How to Sort an Arraylist of Objects by a Property
What Is the Cross-Platform Way of Obtaining the Path to the Local Application Data Directory