Search code examples
javafilenamesprogram-entry-point

what is happening when a class with access modifier public when a java file with file name and class name different


I just a wrote a code like this with file name b.java

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

it gives error like this

error: class a is public, should be declared in a file named a.java

if i remove access modifier public in front of class it is running fine. is there a other solution to achieve i don't want to change the names of class or file name unless there is a big reason.

If so please explain me the reason. why we should give the name of file and name of the class with same name.


Solution

  • If you define a class as public, then class name should match the file name.

    The reason we define any class as public is to make it accessible from other classes or code in other packages.

    This rule of naming file name after its class name makes it easy for the compiler to find the class.

    Also in JAVA, we can have only one public class in a file.