41. Hooking unnamed classes and instance main methods
Imagine that you have to initiate a student in Java. The classical approach of introducing Java is to show the student a Hello World! Example, as follows:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
This is the simplest Java example but it is not simple to explain to the student what public
or static
or String[]
are. The ceremony involved in this simple example may scare the student – if this is a simple example, then how is it a more complex one?
Fortunately, starting with JDK 21 (JEP 445), we have instance main methods, which is a preview feature that allows us to shorten the previous example as follows:
public class HelloWorld {
void main() {
System.out.println("Hello World!");
}
}
We can even go further and remove the explicit class declaration as well. This feature is known as unnamed classes. An unnamed class resides in the unnamed package that resides in the unnamed module:
void main() {
System.out.println("Hello World!");
}
Java will generate the class on our behalf. The name of the class will be the same as the name of the source file.
That’s all we need to introduce Java to a student. I strongly encourage you to read JEP 445 (and the new JEPs that will continue this JDK 21 preview feature work) to discover all the aspects involved in these features.