Sub topic 10
Adding helper classes, records, and interfaces
A compact source file starts as a handful of methods and fields. Most programs soon need a small data type, a helper object, or an interface. This chapter covers how to declare those types in the same file, what the compiler does with them, and the one rule about inner classes that catches most people.
It assumes you know the previous chapters: the implicitly declared class, top-level members, and running a file with java Hello.java. It also assumes you know how nested classes, records, and enums work in ordinary Java.
Types become members of the implicit class
A compact source file may contain class, record, enum, and interface declarations next to its methods and fields. These types are not separate top-level types. The compiler places them inside the implicitly declared class, the same way it places the top-level methods and fields. They are member types of that class.
Here is a small example with a record:
record Point(int x, int y) {
double distanceToOrigin() {
return Math.sqrt(x * x + y * y);
}
}
void main() {
Point p = new Point(3, 4);
IO.println(p + " is " + p.distanceToOrigin() + " from the origin");
}Running this prints Point[x=3, y=4] is 5.0 from the origin.
If you compile a file named Report.java with javac, a nested type Point gets the binary name Report$Point. The compiler writes Report$Point.class next to Report.class. This is the usual naming for member types in Java. The source launcher (java Report.java) keeps these classes in memory and writes no files.
Records, enums, and interfaces are implicitly static
Member records, enums, and interfaces are implicitly static. That is the normal Java rule for nested types, and it holds here. A static member type has no link to an instance of the implicit class. You can create one from any method, static or not.
interface Formatter {
String format(String text);
}
enum Level { INFO, WARN, ERROR }
record Message(Level level, String text) {}
void main() {
Formatter brackets = text -> "[" + text + "]";
Message m = new Message(Level.WARN, "disk almost full");
IO.println(brackets.format(m.level().name()) + " " + m.text());
}The output is [WARN] disk almost full. The interface has one abstract method, so a lambda can implement it, just as in an ordinary class.
Sealed hierarchies
Sealed types work as well. All the permitted subtypes are in one file, so a compact source file suits a small sealed hierarchy with a pattern-matching switch.
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
};
}
void main() {
List<Shape> shapes = List.of(new Circle(1.0), new Square(2.0));
for (Shape s : shapes) {
IO.println(s + " area=" + area(s));
}
}This prints:
Circle[radius=1.0] area=3.141592653589793
Square[side=2.0] area=4.0The switch has no default branch. The compiler knows Circle and Square are the only permitted subtypes, so the switch is exhaustive. If you add a third record to the permits list and forget a case, compilation fails. That is useful in a small program.
Plain classes are inner classes
A plain class declared in a compact source file is a non-static member of the implicit class. That makes it an inner class. Every instance of an inner class holds a reference to an enclosing instance of the implicit class.
This works well from an instance main, because the launcher has already created an instance and new Counter() uses this as the enclosing instance:
String prefix = "Counter";
class Counter {
int count;
void increment() {
count++;
}
String describe() {
return prefix + " is at " + count;
}
}
void main() {
Counter c = new Counter();
c.increment();
c.increment();
IO.println(c.describe());
}The output is Counter is at 2. Note that describe reads prefix, a field of the implicit class. An inner class can do this because of the enclosing instance. This is a real convenience, and it is also the source of the pitfall below.
The static-context pitfall
Compact source files let you declare static void main(). If you do, new Counter() inside it fails to compile, because there is no enclosing instance. Here is the failing version:
class Counter {
int count;
}
static void main() {
Counter c = new Counter();
IO.println(c.count);
}The compiler reports an error similar to non-static variable this cannot be referenced from a static context. There are two fixes:
- Remove
staticfrommain, so the launcher creates an instance. This is usually the best choice in a compact file. - Mark the helper class
static, so it needs no enclosing instance:static class Counter { ... }.
A static helper class cannot read the instance fields of the implicit class. If Counter used prefix above, making it static would stop that code from compiling. You would pass the value in through a constructor or method parameter.
The following table summarizes the rules for member types in a compact source file.
| Declaration | Implicitly static | Can be created in a static method | Can read implicit-class instance fields |
|---|---|---|---|
| `class` | No | No | Yes |
| `static class` | Yes | Yes | No |
| `record` | Yes | Yes | No |
| `enum` | Yes | Yes | No |
| `interface` | Yes | Yes | No |
Name clashes and visibility
The implicit class takes its name from the file name. A member type cannot have the same name as its enclosing class. A file Point.java that declares record Point(int x, int y) {} therefore fails to compile. Pick a file name that differs from every type inside it, for example Geometry.java.
The helper types are also not meant to be used from other files. The implicit class is not something other source code can name in a useful way. Treat every type in a compact source file as private to that file. If you need a type in two files, it belongs in an ordinary class declaration in its own file. The next chapter covers that move.
Two further limits apply to the file as a whole:
- The file has no
packagedeclaration, so all its types are in the unnamed package. - The file needs a launchable
mainmethod. A compact source file with only types and nomainis an error.
Mixing in explicit imports
Types in a compact source file often use library classes. The automatic import of java.base packages covers List, Map, Optional, and many others. Classes from other modules, or from java.base packages you want to name differently, need an ordinary import statement at the top of the file.
import java.time.LocalDate;
record Task(String title, LocalDate due) {}
void main() {
Task t = new Task("Write chapter", LocalDate.of(2026, 12, 1));
IO.println(t);
}This prints Task[title=Write chapter, due=2026-12-01]. Imports must come before the first declaration, as in any Java file.
A practical rule of thumb
Use this order of preference when a program grows:
- Use top-level methods for behavior that needs no state.
- Use records and enums for data and fixed choices.
- Use an interface when two or more types share an operation.
- Use a plain class only when you need mutable state, and remember it is an inner class.
When more than a screenful of types has piled up, or another file needs one of them, the file has outgrown the compact form.
Exercise
A compact source file declares class Box { int value; } and static void main() { Box b = new Box(); IO.println(b.value); }. It fails to compile. Give two different changes that fix it, and say what each one costs.
Show answer
Fix one: remove static from main. The launcher then creates an instance of the implicit class, and new Box() has an enclosing instance. The cost is that main is now an instance method. Fix two: declare static class Box { int value; }. A static member class needs no enclosing instance, so new Box() works in a static method. The cost is that Box can no longer read the instance fields of the implicit class.
Exercise
You save a file as Point.java containing record Point(int x, int y) {} and void main() { IO.println(new Point(1, 2)); }. Why does it fail, and how do you fix it?
Show answer
The implicit class is named Point after the file, and a member type cannot have the same name as its enclosing class. Rename the file, for example to Geometry.java, or rename the record.