Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Is there any way to compile a java program without having the java file name with its base class name.

If so, please explain..

like image 726
Hulk Avatar asked Dec 03 '09 18:12

Hulk


People also ask

Can you save a Java source file by another name than the class name?

Yes,it is possible to compile a java source file with different file name but you need to make sure none of the classes defined inside are public...

Why does Java file name must be same as public class name?

class (byte code) without any error message since the class is not public. The myth about the file name and class name should be same only when the class is declared in public. Now, this . class file can be executed.

Do classes have to be in different files Java?

It is technically legal to have multiple Java top level classes in one file. However this is considered to be bad practice (in most cases), and some Java tools may not work if you do this.

Can a class name be same as package Java?

awt package. Still, the compiler allows both classes to have the same name if they are in different packages. The fully qualified name of each Rectangle class includes the package name.


1 Answers

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.

like image 198
ved Avatar answered Oct 05 '22 23:10

ved