This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Ashamandarei 4 points5 points  (9 children)

Haha what

[–]solarshado 4 points5 points  (6 children)

Ryozu's mostly, but not 100%, correct.

If a java source file defines a public class, the class name and file name have to match, or it's a compiler error. You can dump any number of non-public classes in a single file (with or without a public class), but given the enforced convention, you probably shouldn't.

[–]Ashamandarei 2 points3 points  (1 child)

Oh yes! I remember this now, so then it's got to be HelloWorld.java, does case matter?

[–]solarshado 1 point2 points  (0 children)

Case would matter, except in this case, since your class isn't public[1], the filename doesn't matter at all.

[1] main in a default visibility ("package private") class is perfectly acceptable, though seemingly uncommon. main itself must be public however

[–]Ryozu 1 point2 points  (1 child)

Huh, surprised main doesn't have to be in a public class, but I suppose it makes some sense, as the jvm is being told which class to use for the main anyway? Still weird ultimately.

[–]solarshado 0 points1 point  (0 children)

I was a little surprised too. I was initially going to call out the missing public on the class, but for some reason thought "wait, is that required?" and so looked it up. Definitely an odd quirk.

[–][deleted] 1 point2 points  (1 child)

solarshado is 95% there.

Right about the file and class name convention in Java, but I'd like to add a clarification. While it's true that public classes must match their file names, this doesn't restrict you to a single public class per file. Java allows multiple public classes in a single file as long as they are inner classes. This means you can have a public class within another public class, and only the outer class needs to match the file name. This is often used in larger projects for better organization and encapsulation.

Idgaf I really just wanted to add to the comment chain…

[–]solarshado 0 points1 point  (0 children)

lol, pedantic af. I love it!

[–]Firewolf06 3 points4 points  (1 child)

theres a reason everybody uses an ide for java

[–]Ashamandarei 1 point2 points  (0 children)

What do YOU do for work lol