Can Java Files Contain Multiple Classes?
Java allows multiple classes to coexist within a single Java file. While this is not a common practice, understanding the concept can benefit programmers.
Why Include Multiple Classes in One Java File?
Including multiple classes in a single file serves the purpose of grouping related functionality together, such as:
Limitations on Multiple Classes
However, there are restrictions on multiple classes in a Java file:
Achieving Multiple Classes (Non-Public Case)
It is possible to create non-public inner classes within a public top-level class. These inner classes can access private members of the enclosing class.
Example:
<code class="java">// File: Example.java public class Example { private String name; class InnerClass { public String getName() { return name; // Can access private members of Example class } } }</code>
Note: Inner classes are discussed separately and are not considered multiple top-level classes.
The above is the detailed content of Can a Single Java File Hold Multiple Classes?. For more information, please follow other related articles on the PHP Chinese website!