I know that the name of the public
class declared in a java file must be same as its file name. But I wonder how this is not giving me a compilation error, rather it is running successfully.
class Foo //<-- this can be any name...
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
I know that the default access is package private
. For the above program, the class name and the file name need not be same. It is executing correctly, rather than a compiler error.
Can anyone throw some light? Thank you.
EDIT:
Now I get it! But another question struck me. What happens when there are two such classes in the same file?
Well, I thought a .class
file will be generated out of the class that has implemented main
method. There wasn't any compilation error, but to my surprise there wasn't any .class
file generated either. Why is that so?
Yes, that's absolutely fine. Even for public classes, this is a compiler-specific optional restriction.
From section 7.6 of the JLS:
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).
Note the second bullet point - when your class isn't public, this restriction isn't applicable.
EDIT: From the updated question...
What happens when there are two such classes in the same file?
Class files are generated based on class names. The presence of a main
method is completely irrelevant to this, as is the original source file name. A class file certainly should have been generated if compilation succeeded. Without sample code to reproduce the problem, we can't tell what happened really.
See more on this question at Stackoverflow