Is the class name the same as the file name in java?

in java, the filename must be the same as the main class. This is a way to tell the compiler that this is the entry point for you. but why does this work:

class xyz{
public static void main(String[] args){
System.out.println("a");
}
}

      

even when saved with a different file name.

And why is this thing not being saved when saving with a different filename:

public class xyz{
public static void main(String[] args){
System.out.println("a");
}
}

      

+3


source to share


2 answers


the public classes must be in the file with the correct filename. Non-public classes can be in any file you want. Even several classes in the same file, if convenient.



+9


source


Note that:

class xyz

      

It is not a public class, so it cannot be captured outside the file. Therefore, it should not have the same name. But in this case:



public class xyz

      

You have a public class that it will receive from outside the file, so it must have the same name.

Conclusion: public classes need the filename to be the same as the class.

+1


source







All Articles