Can a java file have more than one class?

yesraaj picture yesraaj · Jun 9, 2009 · Viewed 152k times · Source

What is the purpose of having more than one class in a Java file ? I am new to Java.

Edited: That can be achieved by creating a inner class inside a public class, right?

Answer

Sean Reilly picture Sean Reilly · Jun 9, 2009

Yes, it can. However, there can only be one public top-level class per .java file, and public top-level classes must have the same name as the source file.

The purpose of including multiple classes in one source file is to bundle related support functionality (internal data structures, support classes, etc) together with the main public class. Note that it is always OK not to do this--the only effect is on the readability (or not) of your code.