4

Why do we have to save a file with the name same as that of class name of a public class?

public class Indian{ 
     public static void main (String args []){
          System.out.println ("i am a programmer");
     }
}

This class must be saved with the name Indian.Why so, is it a convention??

utkarsh
  • 409
  • 5
  • 7
  • Check out this post: http://stackoverflow.com/questions/10442758/why-must-a-java-file-have-the-same-name-as-its-public-class – hmir Mar 23 '15 at 20:37
  • If it were so that was for users convinience then the compiler must not give error...but it does so this means that it is not a practice but made mandatory by the compiler....is there any technical logic to it?? – utkarsh Mar 23 '15 at 20:39

2 Answers2

5

Because it's a constraint imposed by the Java compiler. Why is it so? For order, simply. Imagine a huge project with 300 classes, and all of them containing classes with different names.

Michał Szydłowski
  • 3,261
  • 5
  • 33
  • 55
2

First, this applies only to public classes; package-private classes can go into files of any name. For public classes this is a convention, along the same lines as the placement of files in directories that mirror the structure of your packages, and using .java extension.

This is done so that Java compiler can find classes without examining all Java files in the folder.

Note that the convention does not need to be universal: Java supplies a standard that is available to anyone to implement, so one could build a system where Java source files are placed in a database or in a cloud instead of a regular file system. Developers of this Java implementation could theoretically come up with a different convention altogether, or not use any conventions at all.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523