Sub topic 11
Growing a script into a full class
This chapter assumes you can compile and run a Java program from the command line. It also assumes you know the compact source file rules from earlier chapters: top-level methods and fields, the implicitly declared class, and automatic imports. A compact source file suits a small program. Once the program needs a package, several files, or tighter access control, you convert it to an ordinary class. The conversion is mechanical, and you can keep the program working at every step.
Why conversion is safe
A compact source file is not a separate language. The compiler treats its top-level methods and fields as members of an implicitly declared class. That class is final, extends Object, sits in the unnamed package, and takes its name from the file. When you write that class out yourself, you are only making the compiler's work visible.
The conversion therefore has a fixed shape. You add the class header, indent the members, and supply what the compiler used to supply for you. Those things are the imports, a deliberate name, and a deliberate access level.
Stages 1 and 2 keep a single file. Stages 3 and 4 are optional and only matter when the program is no longer a single file.
The starting point
This script counts words, ignoring case. It uses List, Map, and TreeMap without imports, because compact source files import the packages exported by java.base. It also uses a record declared in the same file.
record Entry(String word, int count) {}
Map<String, Integer> counts = new TreeMap<>();
void add(String word) {
counts.merge(word.toLowerCase(), 1, Integer::sum);
}
void main() {
for (String w : List.of("Java", "java", "Kotlin")) {
add(w);
}
counts.forEach((w, c) -> IO.println(new Entry(w, c)));
}Save it as Tally.java. Running java Tally.java prints two lines:
Entry[word=java, count=2]
Entry[word=kotlin, count=1]Stage 1: wrap the members in a class
Write a class declaration named after the file, and move every top-level member inside it. Do not change the member bodies yet. The record Entry becomes a nested record. The field counts stays an instance field, and add and main stay instance methods. The launcher still creates an instance of Tally and calls main() on it, as it did for the implicit class.
The one thing that breaks is name resolution. An ordinary class gets no automatic java.base imports, so you must add them.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Tally {
record Entry(String word, int count) {}
Map<String, Integer> counts = new TreeMap<>();
void add(String word) {
counts.merge(word.toLowerCase(), 1, Integer::sum);
}
void main() {
for (String w : List.of("Java", "java", "Kotlin")) {
add(w);
}
counts.forEach((w, c) -> System.out.println(new Entry(w, c)));
}
}The output is identical. The program has three differences from the script.
- The imports are explicit. You can also write
import java.util.*;, which is closer to what the compact file did, but named imports document dependencies better. - The console call is
System.out.println. TheIOhelper is covered in the callout below. - The class is
public. It does not have to be. A non-public class works when you launch it by name or from a source file, but a public class must live in a file of the same name.
What the conversion changes and what it does not
| Aspect | Compact source file | Explicit class |
|---|---|---|
| Class name | Derived from the file name | You write it; a public class must match the file name |
| Imports | All `java.base` packages, automatically | Only `java.lang` plus what you import |
| Package | Always the unnamed package | Your choice, with a `package` declaration |
| Members | Top-level methods, fields, and types | Inside the class body |
| Access modifiers | Optional and usually omitted | Chosen on purpose for each member |
| Other classes referring to it | Not practical, since the class has no name you wrote | Normal references by name |
| Launch | `java Tally.java`, or compile and run | Same, plus `-cp` and a package-qualified name |
Behavior is the same in every row that touches execution. Members that were instance members stay instance members, field initializers run at construction, and main is chosen by the same rules as before.
Stage 2: tighten the class
Once the class is explicit, you can make decisions the compact form hid. The script left everything package-private by default. The usual changes are:
- Make fields
private, andfinalwhere they are never reassigned. - Make helper methods
privateunless something else needs them. - Keep
mainnon-private. The launcher must be able to call it. - Decide whether
mainshould stay an instance method. If the class will be used as a library, astaticmain(String[] args)is often clearer, because the entry point then needs no object.
Applying the first two to Tally gives these members:
public class Tally {
record Entry(String word, int count) {}
private final Map<String, Integer> counts = new TreeMap<>();
private void add(String word) {
counts.merge(word.toLowerCase(), 1, Integer::sum);
}
void main() {
for (String w : List.of("Java", "java", "Kotlin")) {
add(w);
}
counts.forEach((w, c) -> System.out.println(new Entry(w, c)));
}
}Stage 3: move helper types into their own files
In the compact file, Entry was a member of the implicit class. After wrapping, it is a member of Tally, written Tally.Entry from outside. Leaving it nested is fine. Move it out when other classes need it or the file grows long.
A top-level type must be in a file named after it if it is public:
package tally;
public record Entry(String word, int count) {}When you move it, delete the nested declaration from Tally. Because Entry and Tally are in the same package, the new Entry(w, c) call keeps working with no import.
A nested type and a top-level type are not identical. A nested record is implicitly static, so it cannot touch the enclosing instance. A top-level record has the same limitation, because records never capture an enclosing instance. For plain classes, the difference matters. A nested non-static class can read the outer instance's fields, and a top-level class cannot. If a helper class in your script used fields of the implicit class directly, you must pass those values in when you move it.
Stage 4: add a package
Add package tally; as the first statement of each file. Then the directory layout must match for the build tools and for the -cp launch:
src/tally/Tally.java
src/tally/Entry.javaCompile and run from src:
javac -d out tally/Tally.java tally/Entry.java
java -cp out tally.TallyThree things change when you add a package:
- The class name you give the launcher is now
tally.Tally, notTally. java Tally.javastill compiles a single file in source mode, but it does not findEntryunless that file is compiled with it. For packaged, multi-file programs, usejavacand-cp.- Anything the program reads relative to the working directory is unaffected, but any code that used
Tally.class.getResourcewith a relative path now looks inside the package directory.
Gotchas
- Name collisions with
mainoverloads. If you write bothstatic void main(String[] args)andvoid main(), the launcher picks the static one with theString[]parameter first. The instancemain()is only used when no better candidate exists. When you convert a script and add a conventional entry point, check that the oldmainis not silently being ignored. - File name versus class name. The compact file's class name came from the file name. A script named
word-count.javacould not be turned into a legal class name. Rename the file first, since the class name must be a valid identifier. - Declaration order. Instance field initializers in an ordinary class run in textual order. This is the same rule that applied to the implicit class, so it rarely surprises people. If a field initializer calls a method that uses a later field, you get
nullin both forms. - Static members. A compact file may declare
staticmembers, and they carry over unchanged. You do not need to addstaticto an instancemainwhen wrapping. - Unused
maindependencies. If your script calledmainfrom another method (for example, to restart), that still compiles, but it is a signal that the program has grown past script scale.
When not to convert
Do not convert for its own sake. A compact source file is a fine home for a single-file utility, a quick experiment, or a teaching example. Convert when you need a second source file, a package, restricted access, or a reusable type that other code names. If none of those apply, the explicit class adds lines and no capability.
Exercise
A script Report.java has top-level int total = 0;, a record Row(String name, int value), a method void add(Row r), and void main(). It uses ArrayList with no import. You wrap everything in public class Report { ... } and compile. List what fails and the fix, then say what happens to Row and total.
Show answer
The compiler reports cannot find symbol for ArrayList, because ordinary classes get no automatic java.base imports. The fix is import java.util.ArrayList;. Row becomes a nested record, referred to as Report.Row from outside, and it is implicitly static. total stays an instance field, initialized when the launcher creates the Report instance, so behavior is unchanged. Making total private is optional but recommended once the class is explicit.