How Java instance main methods and unnamed classes work
Benefits of unnamed classes and instance main methods
Instance main methods and unnamed classes, coming in Java 21, will forever change how developers learn Java and bootstrap applications. Why? They provide a simple, clean and concise syntax to launch applications.
Developers who create a runnable Java class, be it for a ‘Hello World’ demonstration or to kick off a fully featured enterprise application, will enjoy the following technical benefits when using unnamed classes and instance main methods:
- No class declaration is required.
- No arguments must be passed to the main method.
- Java keywords public and static are no longer required.
Java unnamed classes example
With instance main methods and unnamed classes, a simple HelloWorld Java application looks like this:
void main() { System.out.println("Hello, World!"); }
The new syntax is much more concise than what was previously required to write a standalone application in Java:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
No more public static void main
Java has always been an easy language to learn.
However, several requirements — the need to define a class, declare a String array, use an access modifier and use the static keyword — expose new learners to advanced concepts that can make getting your first Java program up and running an intimidating experience. Easing the learning experience for new users was one of the primary goals of unnamed classes and Java instance methods.
According to the Java Enhancement Proposal 445:
…these changes allow us to write Hello, World! with no access modifiers, no static
modifiers, and no String[]
parameter, so the introduction of these constructs can be postponed until they are needed.
Java vs other languages
Another benefit of the introduction of Java’s instance main methods and unnamed classes is that it further differentiates Java from other languages that use cryptic and confusing notations to kick off a standard application.
For example, to achieve the same results as the succinct Java ‘Hello World’ program written above, a Python programmer must write the following cryptic and verbose code:
def main(): print('Hello, world!', end="") if __name__ == "__main__": main()
Improvements like this help to end the debate over which language has a simpler, easier to understand syntax.
Java 21 preview features
Instance main methods and unnamed classes are a preview feature in Java 21. Other Java 21 preview features preview features include the following:
- Unnamed patterns and variables.
- Scoped values.
- Structured concurrency.
Java has always been easy to learn, but it’s encouraging to see the stewards of the language continue to lower the barrier to entry.
With unnamed classes and instance main methods, Java is easier to learn than ever.