utkarsh
utkarsh

Reputation: 437

Same name for class and file,Why?

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

Upvotes: 4

Views: 608

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

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.

Upvotes: 2

Michał Szydłowski
Michał Szydłowski

Reputation: 3409

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.

Upvotes: 5

Related Questions