Java
Programming
Multiple Class Declarations
Coding Practices
Software Development

Can you have multiple classes in one Java file?

Codemia Knowledge Hub ·

Yes. A single .java file can declare several classes, but only one of them can be public, and that public class must match the filename. The other top-level classes must be package-private (no access modifier). The compiler still produces a separate .class file for each class.

The one public class per file rule

JLS 7.6 lets a compiler require that a public top-level class live in a file named after it, and javac enforces this, so in practice a file can hold at most one public class.

java
1// File: OrderProcessor.java
2import java.util.List;
3
4public class OrderProcessor {  // Must match filename
5    public void process(Order order) {
6        OrderValidator validator = new OrderValidator();
7        if (validator.isValid(order)) {
8            // process the order
9        }
10    }
11}
12
13class OrderValidator {  // Package-private, same file is allowed
14    boolean isValid(Order order) {
15        return order != null && order.getItems().size() > 0;
16    }
17}
18
19class Order {  // Another package-private class in the same file
20    private List<String> items;
21    List<String> getItems() { return items; }
22}

Compiling OrderProcessor.java produces three .class files:

  • OrderProcessor.class
  • OrderValidator.class
  • Order.class

At the bytecode level each class is independent. Sharing a source file is purely a source organization choice, and since deployment tools and classloaders work with .class files, it is invisible at runtime.

The error from two public classes

Declaring a second public class in the same file fails to compile:

java
1// File: MyApp.java
2
3public class MyApp {          // OK: matches filename
4    // ...
5}
6
7public class MyHelper {       // ERROR
8    // ...
9}

javac reports:

text
MyApp.java:5: error: class MyHelper is public, should be declared in a file named MyHelper.java

Eclipse words the same error as "The public type MyHelper must be defined in its own file".

The compiler relies on the filename to locate public classes during compilation. Without that convention it would have to scan every file to find a class definition.

Kinds of class declarations in one file

Public top-level class

java
1// File: UserService.java
2public class UserService {
3    public User findById(long id) { /* ... */ return null; }
4}
5
6class User { }

One per file, visible to all packages. This is the standard case.

Package-private top-level class

java
1// File: UserService.java
2public class UserService {
3    public User findById(long id) {
4        return new UserCache().get(id);
5    }
6}
7
8class UserCache {  // Only visible within the same package
9    User get(long id) { /* ... */ return null; }
10}
11
12class User { }

Visible only within the same package. Useful for implementation details that support the public class.

Package-private does not mean private to the file. Every class in the same package can use it, so a "helper" that another class in the package starts referencing becomes an unintended coupling.

Inner class (non-static nested)

java
1public class LinkedList<T> {
2    private Node<T> head;
3
4    // Inner class: has implicit reference to outer LinkedList instance
5    private class Node<T> {
6        T data;
7        Node<T> next;
8    }
9}

An inner class is tied to an instance of the enclosing class and can access all of its fields and methods, including private ones. It also holds an implicit reference to the enclosing object, which keeps that object from being garbage collected. Use a static nested class unless you need access to the outer instance.

Static nested class

java
1public class Response {
2    private int statusCode;
3    private String body;
4
5    // Static nested class: no reference to outer instance
6    public static class Builder {
7        private int statusCode;
8        private String body;
9
10        public Builder statusCode(int code) {
11            this.statusCode = code;
12            return this;
13        }
14
15        public Builder body(String body) {
16            this.body = body;
17            return this;
18        }
19
20        public Response build() {
21            Response r = new Response();
22            r.statusCode = this.statusCode;
23            r.body = this.body;
24            return r;
25        }
26    }
27}

It behaves like a regular class scoped inside another, and is common for builders, iterators and entry types (like Map.Entry).

Comparison of declaration types

Declaration TypeAccess ModifierVisibilitySeparate .class FileCan Access Outer Instance
Public top-levelpublicAll packagesYesN/A
Package-private top-level(none)Same package onlyYesN/A
Inner classAnyDepends on modifierYes (Outer$Inner.class)Yes
Static nested classAnyDepends on modifierYes (Outer$Nested.class)No
Local class (in method)(none)Enclosing method onlyYes (Outer$1Local.class)Yes (if non-static method)
Anonymous class(none)Expression onlyYes (Outer$1.class)Yes (if non-static context)

When multiple top-level classes make sense

Small, tightly coupled helpers

A helper that is only a few lines long and used only by the file's primary class:

java
1// File: CsvParser.java
2import java.util.ArrayList;
3import java.util.List;
4
5public class CsvParser {
6    public List<CsvRow> parse(String content) {
7        List<CsvRow> rows = new ArrayList<>();
8        for (String line : content.split("\n")) {
9            rows.add(new CsvRow(line.split(",")));
10        }
11        return rows;
12    }
13}
14
15class CsvRow {  // Trivial data holder, only used by CsvParser
16    final String[] columns;
17    CsvRow(String[] columns) { this.columns = columns; }
18    String get(int index) { return columns[index]; }
19}

Sealed class hierarchies (Java 17+)

Sealed classes often define their permitted subclasses in the same file:

java
1// File: Shape.java
2public abstract sealed class Shape permits Circle, Rectangle, Triangle {
3    abstract double area();
4}
5
6final class Circle extends Shape {
7    double radius;
8    Circle(double radius) { this.radius = radius; }
9    double area() { return Math.PI * radius * radius; }
10}
11
12final class Rectangle extends Shape {
13    double width, height;
14    Rectangle(double w, double h) { this.width = w; this.height = h; }
15    double area() { return width * height; }
16}
17
18final class Triangle extends Shape {
19    double base, height;
20    Triangle(double b, double h) { this.base = b; this.height = h; }
21    double area() { return 0.5 * base * height; }
22}

Keeping the whole hierarchy in one place is natural for algebraic data types used with pattern matching.

Same-file placement is a choice, not a requirement: the permits clause can name subclasses in other files, as long as they are in the same package (or, in a named module, the same module).

Prototyping and competitive programming

One file reduces friction when you are prototyping or solving contest problems:

java
1// File: Solution.java
2import java.util.ArrayList;
3import java.util.List;
4
5public class Solution {
6    public static void main(String[] args) {
7        Graph g = new Graph(5);
8        g.addEdge(0, 1);
9        g.addEdge(1, 2);
10        System.out.println(g.bfs(0));
11    }
12}
13
14class Graph {
15    List<List<Integer>> adj;
16    Graph(int n) {
17        adj = new ArrayList<>();
18        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
19    }
20    void addEdge(int u, int v) { adj.get(u).add(v); adj.get(v).add(u); }
21    List<Integer> bfs(int start) { /* ... */ return new ArrayList<>(); }
22}

Why production code uses one class per file

  • IDE navigation. IDEs map filenames to class names. If OrderValidator lives in OrderProcessor.java, "Go to Class" does not lead you to an obvious file.
  • Version control. Changes to OrderValidator show up as diffs on OrderProcessor.java, which makes history harder to follow.
  • Code review. Reviewers expect a class to be in the file with its name. Hunting for package-private classes slows reviews down.
  • Package structure. If many related classes end up in one file, that usually means you need a sub-package. Create it and give each class its own file.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms