• Post Reply Bookmark Topic Watch Topic
  • New Topic

Need clarity on .class/.java naming logic  RSS feed

 
Brendon McFadden
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

I'm a very new starter to java (obviously) and I'd like someone to explain why I was able to create a source file (.java) with a different name to the class and still have it work? Through all the info I could find it shouldn't as it's a public file.

I named my source file Another.java and it looked like:

class Naming

{
public static void main (String[] args)
{
System.out.println("This means it worked... again!");
}
}

I then ran "javac Another.java" which worked, and when running "java Naming" that printed off the text.

Have I done something wrong for this to still work? Or is it expected and just an organisational idea to have the same soruce/class name? From my searches I should get an error?

Thanks.
 
Tim Moores
Saloon Keeper
Posts: 4033
94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would get a compilation error if the class was declared "public", as in "public class Naming".
 
Brendon McFadden
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim Moores wrote:You would get a compilation error if the class was declared "public", as in "public class Naming".


Ahh I see, thank you. So declaring a class and main method as public are two very different things?
 
Tim Moores
Saloon Keeper
Posts: 4033
94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. The main method has in any case a special position, as it's used to run code the command line where there is not (yet) an "object environment".
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The rule about being public and being in a file with the same name only applies to top-level classes.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!