Why do we need to give the same file name as the class name in a public class?
Saumya Purkayastha
Greenhorn
Joined: Mar 27, 2010
Posts: 23
posted
0
I was trying to run a program - phraseOMatic.java which was not working, when I changed the filename to PhraseOMatic.java(which is same as the public class name), it started working.
I got the below error:-
1 error
C:\Program Files\Java\jdk1.6.0_18\bin>javac C:\Users\Sony\Desktop\java\phraseOMatic.java
C:\Users\Sony\Desktop\java\phraseOMatic.java:1: class PhraseOMatic is public, should be declared in a file named PhraseOMatic.java
public class PhraseOMatic {
^
Why is it that in a public class we have to name the .java file exactly as the class name.
I was able to compile this program after I changed the file name from phrasOMatic.java to PhraseOMatic.java
I have noticed that if we do not specify the class as public, the file name can be totally different from the class name.
Thanks and Regards, Saumya Purkayastha - Sam
Specialist - Internet Marketing
Ireneusz Kordal
Ranch Hand
Joined: Jun 21, 2008
Posts: 423
posted
0
Saumya Purkayastha wrote:
Why is it that in a public class we have to name the .java file exactly as the class name.
This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.
Saumya Purkayastha
Greenhorn
Joined: Mar 27, 2010
Posts: 23
posted
0
Is this restriction only for Public class?
If so why is this restriction not there for non-public classes in Java specification?
Sorry if I am too inquisitive. Beginners often want to know "why?"
If you know the answer please let me know rather than asking me to test. This is a request because it will be helpful for the community other than me. I have tested as per your recommendations and found the following results:-
I created a simple program and tried to use different access specifiers for the class definition. Below are the results:-
Public - In this case the class name has to be same as the filename.
Not specified anything - The filename and class name need not match.
Protected - It does not allow me to use this.
Private - It does not allow me to use this.
This is my 4th program and so I dont know the reason to why this is happening. I am sure I will find this either in this forum soon or in my future days of studying java.
I have great expectations from this forum. Gimme a satisfactory answer.