Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does java not allow multiple public classes in a java file ?  RSS feed

 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why should a public class be declared/kept in a java file with the same name as the class ?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just because that's how the designers of the Java language designed it. They probably thought that would make it easier to find the source of a specific class - if you know the class name, you know for what file to look. There's no technical reason why this would be necessary.
 
Buddhika Mawella
Ranch Hand
Posts: 40
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not even public class, if you define a public interface or a enum in java, you should give them a dedicated file with the same name of the interface or enum.
 
Campbell Ritchie
Marshal
Posts: 55687
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please search; this question comes up quite frequently.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Oak specification indicated it was "necessary for efficient package importation."

Ref: Java History 101: Once Upon an Oak.
 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
marc weber wrote:The Oak specification indicated it was "necessary for efficient package importation."

Ref: Java History 101: Once Upon an Oak.


Thanks for the link. I visited it and saw this : "The compiler would have to make an additional pass through all the compilation units (.java files) to figure out which classes were where, which would make the compilation even slower. "

The meaning of "...additional pass through all..." is not clear. Can you tell me what it means ?
 
Campbell Ritchie
Marshal
Posts: 55687
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a particular class is not found in the current file, the compiler would have to open and parse every .java file in the directory to find it.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!