Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same name for class and file,Why?

Tags:

java

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??

like image 515
utkarsh Avatar asked Mar 16 '23 15:03

utkarsh


2 Answers

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.

like image 149
Michał Szydłowski Avatar answered Mar 27 '23 19:03

Michał Szydłowski


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.

like image 34
Sergey Kalinichenko Avatar answered Mar 27 '23 18:03

Sergey Kalinichenko