Yes, it is mandatory in Java. Each public class has to be in a separate file named exactly the same way as the class.
See this question about it. The Java language specification writes that this is not 100% mandatory for compilers, but they usually do that. And since it is a good thing, and is noted in the spec, all compilers do it.
When packages are stored in a file system (§7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav)
If you want to have multiple classes in the same file, that's a different story. You can do it in two ways:
- declare them as package-private classes with
class Foo
after the body of the main class. You can have any number of non-public classes in the same file
- declare them as static inner classes:
public static class InnerFoo
inside the main class body. That way they will be visible to other classes by FooClass.InnerFoo