Can I compile a java file with a different name than the class?
No, the public class name must match the file name. Inner, non public, class names may differ.
To answer the question take a look at this example:
Create a file Sample.java
class A
{
public static void main(String args[])
{
String str[] = {""};
System.out.println("hi");
B.main(str);
}
}
class B
{
public static void main(String args[])
{
System.out.println("hello");
}
}
now you compile it as javac Sample.java
and run as java A
then output will be
hi
hello
or you run as java B
then output will be hello
Notice that none of the classes are marked public
therefore giving them default
access. Files without any public classes have no file naming restrictions.
As long as you don't have a public class in your source file, you can name your source file to any name and can compile. But, if you have a public class in your source file, that file should have the name same as your class name. Otherwise, compiler will throw an error.
Example:
Filename: TestFileName.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello,World\n");
}
}
Compiling: javac TestFileName.java
Error:
TestFileName.java:1: class HelloWorld is public, should be declared in a file named HelloWorld.java
public class HelloWorld
^
1 error
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 :)