Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class name same as filename in java? [duplicate]

Tags:

java

in java, filename should be same as that of main class. It is the way of telling compiler that this is the entry point for you. but why this thing works:

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

even when saved with different filename.

And why this thing does not when saved with diffrent filename:

public class xyz{
public static void main(String[] args){
System.out.println("a");
}
}
like image 895
Moose Avatar asked Apr 30 '26 13:04

Moose


2 Answers

public classes have to be in a file with the correct filename. Non-public classes can be in any file you want. Even multiple classes in the same file if it is convenient.

like image 195
khelwood Avatar answered May 03 '26 01:05

khelwood


Note that:

class xyz

Is not a public class so it cannot be acessed from outside of the file. Therefor it does not need to have the same name. But in this case:

public class xyz

You do have a public classe, that it gonna be acessed from outside of the file, so it does need to have the same name.

Conclusion: public classes need to have the file name exatly the same as the class.

like image 29
AndreDuarte Avatar answered May 03 '26 01:05

AndreDuarte