0

Could anyone please explain to me the concept of why is it absolutely necessary to save the Java program with the name of the public class defined in it?

Saving the following program with a name other than Pattern.java causes an error. Why?

public class Pattern
{
    public static void main(String Args[])
    {

    }
}

Saved as: "Ex.java" Error: class Pattern is public, should be declared in a file named Pattern.java public class Pattern

Manish Negi
  • 113
  • 1
  • 12
  • 1
    Actually, a Java source file can have more than one class inside it, but can only have one _public_ class name, which has to match the source name. This convention makes it easy for things like IDEs to get around your code base. – Tim Biegeleisen Jul 06 '18 at 11:32
  • What are you using to save it? And what is the error message? – musefan Jul 06 '18 at 11:32
  • My question was if one among those multiple classes is specified as public then it is mandatory to save the program with the public class's name otherwise it gives an error. – Manish Negi Jul 06 '18 at 11:34
  • @TimBiegeleisen The key word is **public**. It's not possible to have multiple **public** class definitions, and that's exactly what OP said. – Michael Jul 06 '18 at 11:34
  • 1
    @ManishNegi - Just FYI, if you *don't* make that class `public`, you can call the file anything you want (`Foo.java`), compile it, and then run it via `java Pattern`. The `java` tool doesn't care whether the class is `public`. But if the class **is** `public`, it has to be in a file with the name of the class, for reasons described in the linked question's answers. – T.J. Crowder Jul 06 '18 at 11:36

0 Answers0