Apologies if my question was not clear.
All of you have just repeated what I also observed.But, I wanted to
know why is it so?
I wanted to know why that constraint(file name having the same name as
the class name) exists when I make it as public and not when it has
the default access specifier.
You can have one single file F.java with many (e.g. 3: A, B, C)
classes with default access specifier but (at max) only one public
class (e.g. F).
File F.java:
/////////////////////////////////////////////////////////////////////
class A{public static void main(String[]a){System.out.println("A");}}
class B{public static void main(String[]a){System.out.println("B");}}
class C{public static void main(String[]a){System.out.println("C");}}
public
class F{public static void main(String[]a){System.out.println("F");}}
/////////////////////////////////////////////////////////////////////
and you can invoke them in one of the following 4 ways:
prompt> java A
A
prompt> java B
B
prompt> java C
C
prompt> java F
F
but you cannot add another public class G to file F.java:
/////////////////////////////////////////////////////////////////////
class A{public static void main(String[]a){System.out.println("A");}}
class B{public static void main(String[]a){System.out.println("B");}}
class C{public static void main(String[]a){System.out.println("C");}}
public
class F{public static void main(String[]a){System.out.println("F");}}
public
class G{public static void main(String[]a){System.out.println("G");}}
/////////////////////////////////////////////////////////////////////
Why this?
Because a compiler acting on compilation units residing
on a filesystem may choose to enforce the restriction
that there must be at most one public class per compilation unit.
This optional restriction is allowed by Java Language Specification,
<
http://java.sun.com/docs/books/jls/second_edition/html/packages.doc.html#73491>.
As pointed out by the Java Language Specification:
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.
This restriction is optional, as pointed out rkm in message
<
http://makeashorterlink.com/?C31E555A5>.
This restriction is forbidden by Java Language Specification
when packages are stored in databases (instead of filesystem):
<
http://java.sun.com/docs/books/jls/second_edition/html/packages.doc.html#20150>.
I hope this answer clarify your doubts.