Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

source file?

 
Palash Kumar
Ranch Hand
Posts: 33
MyEclipse IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There can be only one public class per source code file.

WHY....???
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would you want to use more ?

First of all, you can create public inner classes (even static that do not share any relationship with the enclosing class.

As for fully-fledged 'Top-Level-Classes', it is possible to only have one public class per file).

Why?

First of all it is always better in terms of source control to have each class in a separate file.
Imagine you put 5 classes into one file, it quickly becomes harder to still have the picture of your project.
There are, of course, exceptions. If there is a small helper class that's sole purpose is to do a little thing in the enclosing class, then an InnerClass or Anonymous class would just do fine.

Second of all, more than one class per file ultimately results in more code. Which is not what you want due to code maintainability and the concept of cohesion.

Hence it might be that the architects of Java simply have decided to restrict java files to have one Top-Level-Class per source file.
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Palash Kumar wrote:There can be only one public class per source code file.

WHY....???


If you search the forum you will find that people have tried to answer this question before
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The source file name must match the name of the key class in the source file. With two public classes, what would the file be named?

-Cameron McKenzie
 
Palash Kumar
Ranch Hand
Posts: 33
MyEclipse IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why it is necessary to name the file as of public class.....?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
without really knowing, I think it's for the ClassLoader.

Imagine you have a package with 46 classes in it.

then you instantiate new FancyClass();

Without doing a lot of research the ClassLoader knows that he is looking for FancyClass.class
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic