Home  >  Article  >  Java  >  Can a Single Java File Hold Multiple Classes?

Can a Single Java File Hold Multiple Classes?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 14:13:02799browse

Can a Single Java File Hold Multiple Classes?

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:

  • Internal data structures
  • Support classes for the main class

Limitations on Multiple Classes

However, there are restrictions on multiple classes in a Java file:

  • Only one public top-level class is permitted.
  • Public top-level class names must match the Java source file name.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn