Sub topic 6
Top-level methods and fields
This chapter assumes you know the basic syntax of Java methods and fields, and that you have seen the previous chapters on instance main methods and compact source files. Here you will learn what happens to the methods and fields you write directly in a compact source file, and where that model surprises people.
Members without a class around them
In a compact source file, you can write methods and fields at the top level. The compiler does not treat them as free-floating functions or global variables. It places all of them inside the implicitly declared class, so they are ordinary members of that class.
String greeting = "Hello";
String greet(String name) {
return greeting + ", " + name + "!";
}
void main() {
IO.println(greet("Java"));
}Save this as Greeter.java and run java Greeter.java. It prints Hello, Java!.
The compiler treats the file as if you had written this:
final class Greeter {
String greeting = "Hello";
String greet(String name) {
return greeting + ", " + name + "!";
}
void main() {
IO.println(greet("Java"));
}
}The first version is shorter, but both mean the same thing. The class name comes from the file name, and the class is final and sits in the unnamed package.
Instance members are the default
A method or field with no static modifier is an instance member, exactly as inside any class. Three consequences follow.
- Fields belong to the one instance the launcher creates, so
maincan read and change them. - Instance methods can call each other and read fields without any qualifier.
thisis available. - Field initializers run in the constructor, in the order they appear in the file.
int count = 0;
void bump() {
count++;
}
void main() {
bump();
bump();
IO.println("count = " + count);
}This prints count = 2. Because the launcher creates only one instance, count behaves like a program-wide variable. It is still an instance field, though. If you later turn the file into a class and create several instances, each one gets its own count.
Static members still work
You can add static to any top-level method or field. Use it for constants and for helpers that need no instance state.
static final int MAX_TRIES = 3;
static int square(int n) {
return n * n;
}
void main() {
for (int i = 1; i <= MAX_TRIES; i++) {
IO.println(i + " squared is " + square(i));
}
}An instance method can call a static method and read a static field. The reverse is not true, as the next section shows.
Mixing static and instance members
Recall from the earlier chapter that the launcher prefers a static main if there is one. If you declare static void main(), the launcher does not create an instance. That choice interacts with your fields.
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. The rule is the same as in any class. A static method has no this, so it cannot reach instance members.
You have two fixes. Drop static from main, which is the usual choice in a compact file. Or make count static as well.
Declaration order
Methods can appear in any order. main may call a method declared further down the file, as it can in any class.
Field initializers are different. A field initializer cannot use a field declared after it by simple name, because the compiler rejects an illegal forward reference.
int a = b + 1;
int b = 2;
void main() {
IO.println(a);
}This fails with illegal forward reference. Swap the two declarations and it compiles, printing 3.
The same ordering rule appears in ordinary classes. People notice it more in compact files because the fields often sit at the top of a short script and are easy to rearrange by accident.
Access modifiers
You can put private, protected, or public on top-level members, and you can leave them off. These modifiers behave as they would in a class, but they matter less here. Nothing outside the file can see the implicit class by name, and the program has no other classes in separate files. The effect shows up only when the file declares nested types, which can see the outer class's private members.
Two modifiers help in practice:
privatedocuments that a helper is internal.finalon a field works as usual. Afinalinstance field must be assigned in its initializer, because the file has no constructor in which to assign it.
Overloading, generics, and varargs
Top-level methods have the full power of ordinary methods. You can overload them, make them generic, and use varargs.
int sum(int... values) {
int total = 0;
for (int v : values) {
total += v;
}
return total;
}
<T> void show(String label, T value) {
IO.println(label + ": " + value);
}
void main() {
show("sum", sum(1, 2, 3, 4));
show("none", sum());
}This prints sum: 10 and none: 0. The List type you use in such programs needs no import, because compact source files import the java.base packages automatically.
Nested types are members too
Classes, records, enums, and interfaces that you declare in the file are not separate top-level types. They are member types of the implicit class. Records, enums, and interfaces are implicitly static, so they need no instance. An ordinary nested class is an inner class unless you mark it static.
int base = 10;
class Adder {
int add(int n) {
return base + n;
}
}
void main() {
Adder adder = new Adder();
IO.println(adder.add(5));
}This prints 15. Adder is an inner class, so it can read base from the enclosing instance. The call new Adder() works inside main because main is an instance method and supplies the enclosing instance. A later chapter covers helper types in more detail.
What you cannot put at the top level
Only declarations are allowed at the top level of a compact source file. Statements are not.
| Written at top level | Result |
|---|---|
| Method declaration | Allowed. Becomes a member of the implicit class. |
| Field declaration | Allowed. Becomes a member of the implicit class. |
| Class, record, enum, interface | Allowed. Becomes a member type. |
| `import` declaration | Allowed, but only before the members. |
| `package` declaration | Not allowed. The class is in the unnamed package. |
| Statement such as `IO.println("hi");` | Compile error. Put it in a method. |
| Field declared with `var` | Compile error. `var` is for local variables. |
Two further limits are worth remembering.
- A compact source file must contain a launchable
mainmethod. Without one, the compiler reports an error, and the file is not a program. - The implicit class has no name you can rely on from other source files. Other classes cannot refer to it, so a compact file is a place to write a standalone program, not a reusable library.
Common pitfalls
- Static
mainwith instance fields. This is the error shown earlier. Removestaticfrommain. - A forgotten return type. A method such as
greet(String name) { ... }with no return type is rejected, because it looks like a constructor. Always writevoidor a type. - Statements at the top level. Beginners coming from scripting languages write
IO.println(...)directly in the file. Wrap it invoid main(). - A name clash with the file name. The implicit class takes its name from the file. A member type with the same name as the file causes a conflict. Pick different names for nested types.
- Shadowing a field with a local variable. A parameter named
greetinghides the fieldgreeting. Usethis.greetingto reach the field.
Exercise
This file is saved as Counter.java. It fails to compile. Explain why, and give two different fixes. int total = 0; static void main() { total += 5; IO.println(total); }
Show answer
The static method main has no instance, so it cannot access the instance field total. The compiler reports that a non-static variable cannot be referenced from a static context. Fix one: remove static from main, so the launcher creates an instance and main can use total. Fix two: declare the field as static int total = 0; so the static method can access it.
Exercise
What does this file print, and what change makes it compile if it does not? int a = b * 2; int b = 4; void main() { IO.println(a); }
Show answer
It does not compile, because the initializer of a uses b before b is declared, which is an illegal forward reference. Moving int b = 4; above int a = b * 2; fixes it, and the program then prints 8.