One Public Top-Level Type per File

ID

java.one_public_class_per_file

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

best-practice, code-style

Description

Reports the second and subsequent public top-level type declarations in a single source file. The Java Language Specification requires that a source file contain at most one public top-level class, interface, or enum, and that its name match the file name.

Rationale

Placing multiple public types in one file breaks the standard one-to-one mapping between file names and public types. This makes classes harder to locate, confuses build tools that rely on the convention, and violates the JLS rule that will cause compilation errors in most environments.

// File: Foo.java
public class Foo { }        // OK
public class Bar { }        // Violation — second public type

Remediation

Move each public type into its own source file named after the type.

// File: Foo.java
public class Foo { }

// File: Bar.java  (separate file)
public class Bar { }