• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A very simple question (Please Answer)

 
Pattu Babu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why there is a restriction that, if a public class is there inside a source file, then the source file name has to be the same as the public class name.
 
Nigel Browne
Ranch Hand
Posts: 703
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rules had to be made for how the javac program would function. Rule number one was only one public class per .java file.
[ May 25, 2005: Message edited by: Nigel Browne ]
 
Pattu Babu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nigel Browne,
But, why such a confusion for the compiler in case of publc classes alone and not for the default classes.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm afraid that the answer remains "because those are the rules". What requirement do you have which needs two public class definitions in the one file?
 
Nigel Browne
Ranch Hand
Posts: 703
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is perfectly legal to write the following:
You could then compile and run this class

You can also do the following: You can then save this file as Hello.java and compile and run each of the two Test classes, but you can't have two public classes in one .java file because that is the rule and the compiler will not let you get away with it.
[ May 25, 2005: Message edited by: Nigel Browne ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a convenience for the compiler. If you reference a class called BowlingGame the compiler knows to look for the source in a file called BowlingGame.java and the compiled code in a file called BowlingGame.class. If not for that rule the compiler might have to look inside all the files in the current directory or your whole classpath to find the one that says "class BowlingGame". Oh, and it's more convenient for us humans, too!
[ May 25, 2005: Message edited by: Stan James ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic