Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Your observation is correct. If the class is not public, the name of the class does not need to match the file name. When you don't have a public class in your file, you can name your file as you like.

If you say have a source file Test003.java and you define in it
two non-public classes AAA and BBB, there are no compilation
errors and two class files are generated: AAA.class and BBB.class.

So all is good.

01/20/2014  06:27 AM               238 AAA.class
01/20/2014  06:27 AM               238 BBB.class

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top