Sub topic 5
The class the compiler declares for you
This chapter assumes you know how a class, a field, and a method relate. It also assumes you have seen public static void main(String[] args). A compact source file has no class declaration, yet the JVM only runs classes. This chapter covers what the compiler builds around your code, the rules that class follows, and the errors you get when your code doesn't fit them.
The rule: wrap the members, then compile
A compact source file is a file with at least one top-level method or field, which are members declared outside any class. When javac sees one, it declares a class and places every top-level member inside it. This class is called the implicitly declared class.
Take this file, saved as Hello.java:
void main() {
IO.println("Hello, world!");
}The compiler treats it as if you had written the following. The class is not public, and it is final.
final class Hello {
void main() {
IO.println("Hello, world!");
}
}Everything else follows from this wrapping.
The properties of the generated class
The language specification fixes these properties, so you can rely on them.
| Property | Value |
|---|---|
| Name | The file name without `.java`. `Hello.java` gives `Hello`. |
| Package | The unnamed package. |
| Superclass | `Object`. It cannot extend another class. |
| Interfaces | None. It cannot implement any. |
| Modifiers | `final`. Not `public`. |
| Constructor | The default no-argument constructor, because you cannot declare one. |
| Members | Your top-level fields and methods, plus any types declared in the file. |
Because the file name becomes the class name, it must be a valid Java identifier. Hello.java works. A name such as hello-world.java does not, because the hyphen cannot appear in a class name.
You can check these properties with reflection. Save this as Demo.java:
void main() {
IO.println(getClass().getName());
IO.println(getClass().getSuperclass().getName());
IO.println(Modifier.isFinal(getClass().getModifiers()));
}Run it with java Demo.java. It prints Demo, then java.lang.Object, then true. The call to getClass() works because main is an instance method, so this exists. Modifier needs no import because the java.base packages are imported automatically. That is covered in a later chapter.
Inspecting the result with javap
You can also look at the compiled class. Compile the file, then disassemble it:
javac Hello.java
javap -p HelloThe output looks like this:
Compiled from "Hello.java"
final class Hello {
Hello();
void main();
}The final modifier, the package-private constructor, and the instance main are all visible. The constructor is package-private because it takes the access of its class, and the class is not public.
Fields and methods are instance members by default
A top-level declaration with no static modifier becomes an instance member of the generated class. This matches ordinary class rules, so nothing new applies.
int count = 0;
int next() {
count++;
return count;
}
void main() {
next();
next();
IO.println("Calls so far: " + count);
}This prints Calls so far: 2. Here main is an instance method. The launcher creates one Hello-style object, with the file name as the class name, and calls main on it. count is a field of that object, and next reads and writes it through the implicit this.
You may write static on any top-level member, including main:
static int twice(int n) {
return n * 2;
}
static void main() {
IO.println(twice(21));
}This prints 42. A static main skips instance creation, and the launcher calls it directly. Mixing the two styles follows the usual rule. A static method cannot touch instance fields without an object.
int count = 0;
static void main() {
count++;
}This fails to compile with an error such as non-static variable count cannot be referenced from a static context. This is the most common error in compact files. Either remove static from main, or make the field static.
Types declared in the file become member classes
Classes, records, enums, and interfaces that you declare in the file are not separate top-level classes. They become members of the implicitly declared class, and this affects how you use them.
record Point(int x, int y) {}
void main() {
IO.println(new Point(1, 2));
}This prints Point[x=1, y=2]. The compiled class is named Hello$Point, or whatever your file name is followed by $Point.
Records, enums, and interfaces are implicitly static when nested. A plain class is different, because a nested class without static is an inner class. Each instance holds a reference to an instance of the enclosing class.
class Counter {
int n;
void inc() { n++; }
}
void main() {
Counter c = new Counter();
c.inc();
IO.println(c.n);
}This works and prints 1. The new Counter() expression runs inside an instance method, so an enclosing object is available through this.
The same code fails when main is static, because there is no enclosing instance:
class Counter {
int n;
}
static void main() {
Counter c = new Counter();
}javac rejects this with non-static variable this cannot be referenced from a static context. There are two fixes. Declare the helper as static class Counter, or keep main as an instance method.
Name clashes
A member class cannot share its name with the class that encloses it. If Hello.java also declares class Hello {}, the compiler reports a conflict, because the implicit class is already named Hello. Choose a different name for the helper or for the file.
A launchable main method is required
The compiler insists that the implicitly declared class can be launched. If the file has top-level members but no method the launcher accepts as main, compilation fails with an error that says the class does not have a main method. Launcher selection of main was covered earlier. Briefly, it prefers static void main(String[]), then static void main(), then the instance forms. For the instance forms the class needs an accessible no-argument constructor, and the implicit class always has one.
A file with no top-level fields or methods is not compact. It is an ordinary compilation unit whose classes you declared yourself. The compiler adds no wrapper class in that case.
What you cannot do
The implicit class is deliberately closed. These restrictions follow from the table above.
- You cannot name the class in code. Nothing outside the file can refer to
Helloas a dependency, so other classes cannot use it by name. Treat the file as an entry point, not a library. - You cannot declare a constructor. There is no class header to put one under, so initialize state with field initializers or inside
main. - You cannot change the header. There is no place for
extends,implements,public,abstract, or annotations on the class. Doing any of these means writing an explicit class declaration. - You cannot place statements at the top level. Only declarations are allowed outside methods, so a bare
IO.println("hi");is a syntax error. - You get one implicit class per file. All top-level members join the same class.
Moving to an explicit class
Wrapping the members in a class declaration gives the same behavior, which is the step to take when a program outgrows the compact form. Moving Counter out of the implicit class is also easy, since it becomes a top-level class:
public class Hello {
void main() {
IO.println("Hello, world!");
}
}Once a class header exists, you can add public, an extends clause, constructors, and a package declaration.
Exercise
A compact source file Tally.java contains int total;, a static main() that executes total++;, and nothing else. Why does it fail to compile, and what are two ways to fix it?
Show answer
total is an instance field of the implicitly declared class Tally, and a static method cannot access an instance field without an object. One fix is to remove static from main, so the launcher creates an instance and main can use total. The other is to declare the field as static int total;.
Exercise
In Hello.java, you declare class Helper {} and a static void main() that runs new Helper();. The compiler rejects the code. What is the cause, and which two changes would make it compile?
Show answer
Helper is an inner class of the implicit class Hello, so creating it requires an enclosing Hello instance. A static main has no this. Declaring static class Helper {} removes the need for an enclosing instance. Changing main to an instance method also works, because this is then available.