I'm new to Java. I want to know why Java doesn't give an error and lets the compiler compile it when I write as class class-name without public and giving the file name different from that class name. When I add public before class and then giving the different file name from class name, it gives me error. Why does that happen?
Asked
Active
Viewed 25 times
-1
Mark Rotteveel
- 90,369
- 161
- 124
- 175
Lycan
- 9
- 1
-
3Because public classes need to be in a file named after the class and non-public classes don't. โ Dave Newton May 14 '22 at 18:44
-
Duplicate: [File name and class name different in java](https://stackoverflow.com/questions/19731853/file-name-and-class-name-different-in-java), and also: [Can I compile a java file with a different name than the class?](https://stackoverflow.com/questions/1841847/can-i-compile-a-java-file-with-a-different-name-than-the-class) โ Mark Rotteveel May 14 '22 at 19:00
-
2The specification is [section 7.6 of the Java Language Specification 17](https://docs.oracle.com/javase/specs/jls/se17/html/jls-7.html#jls-7.6): _"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 class or interface is not found in a file under a name composed of the class or interface name plus an extension (such as .java or .jav) if either of the following is true: [..] * The class or interface is declared public (and therefore is potentially accessible from code in other packages). "_ โ Mark Rotteveel May 14 '22 at 19:06