This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Only one public class per source file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Only one public class per source file" Watch "Only one public class per source file" New topic
Author

Only one public class per source file

Vrushank Shukla
Greenhorn

Joined: Sep 10, 2012
Posts: 14
Can anyone explain the reason for only one public class per source file?

I read many post about it, but still I can't get it. Please explain me.
Keerthana Bijoor
Greenhorn

Joined: Mar 01, 2013
Posts: 2
This public class acts as the initial class from where the JVM instance for the java program is begun.So when you provide more than one public class in a program the compiler itself stops you by throwing an error. This is because later you can't confuse the JVM as to which class to be its initial class because only one public class with the public static void main(String args[]) is the initial class for JVM.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

It's just a choice that the inventors of Java made. There's no technical reason that explains why there must be only one public class per source file.

You can debate about why exactly they made that choice, but frankly, that isn't a very interesting discussion - there's not really a final, definitive answer that explains it. Maybe they made the choice to keep things simple and organized - if you're looking for the source code of a public class SomeClass, you know you're going to find it in a file named SomeClass.java. So, this rule makes it easier to find.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Vrushank Shukla
Greenhorn

Joined: Sep 10, 2012
Posts: 14
ok thanks Jesper and Keerthana.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38064
    
  22
Keerthana Bijoor, welcome to the Ranch
 
 
subject: Only one public class per source file
 
Similar Threads
URGENT
Why should there be only one public class per source file
Call a method from another class!!
source file?
Class using Main without declaring itself Public