Sub topic 2
The class the compiler declares for you
Assume you know ordinary Java classes, fields, methods, and the traditional main method. This chapter uses Java 25, where compact source files and instance main methods are final features.
The implicitly declared class
A compact source file has methods and fields without an explicit class declaration. The compiler creates an implicitly declared class around those members. The source file name supplies the class name.
// Greeting.java
String greeting = "Hello";
void main() {
IO.println(greeting + ", Java!");
}Running java Greeting.java launches the main method. Conceptually, the compiler treats the file roughly like this:
class Greeting {
String greeting = "Hello";
void main() {
IO.println(greeting + ", Java!");
}
}The generated class is not a separate source file that you edit. It is the compiler's model of the compact file.
Top-level methods and fields
Methods and fields written directly in the compact file become members of the implicit class. They are therefore available to each other like ordinary instance members.
String greeting = "Hello";
String greet(String name) {
return greeting + ", " + name + "!";
}
void main() {
IO.println(greet("Ada"));
}The launcher creates an instance when it runs an instance main method. The method can then read the field and call greet without an object variable.
What is imported automatically
Compact source files implicitly import the public types exported by the java.base module. This includes commonly used types such as List, so this code needs no import java.util.List; line.
void main() {
List<String> names = List.of("Ada", "Grace");
for (String name : names) {
IO.println(name.toUpperCase());
}
}This convenience applies to compact source files. Ordinary class source files still use normal import rules.
Console I/O with `java.lang.IO`
IO provides simple console operations. IO.println writes a line, and IO.readln displays a prompt and reads one input line.
void main() {
String name = IO.readln("Your name: ");
IO.println("Hello, " + name + "!");
}Exercise
In a compact source file, where does a top-level field become a member, and which class supplies IO?
Show answer
The field becomes a member of the implicitly declared class, and IO is java.lang.IO.