Is there any way to compile a java program without having the java file name with its base class name.
If so, please explain..
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...
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With