Java 21 unnamed classes instance main method

Java 21’s Secret Weapons: Instance Main Methods and Unnamed Classes

Learn how to use instance main method and unnamed classes in Java 21 with this beginner-friendly guide. Simplify your code and improve your programming skills today!

Introduction

Java 21 is the latest release of the Java programming language, and it comes with some exciting new features that make it easier and more fun to write Java code. In this blog post, we will focus on two of these features: instance main method and unnamed classes. These features are designed to simplify the learning curve for beginners and allow them to bootstrap a class with minimal syntax. Let’s see how they work and why they are useful.



Instance Main Methods

One of the first things that beginners have to learn when they start coding in Java is how to declare a main method. The main method is the entry point of a Java program, and it is where the execution of the code begins. Traditionally, a main method has to be declared as a public static void method with a String[] parameter, and it has to be inside a public class. For example, if we want to create a main method that simply prints a hello world message, we have to write something like this:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
Main.java

As you can see, there is a lot of boilerplate code that we have to write just to define a main method. We have to specify the access modifier (public), the static modifier (static), the return type (void), the method name (main), and the parameter (String[] args). We also have to create a public class (Main) that contains the main method, and save this class in a file with the same name as the class (Main.java).

All of this can be confusing and unnecessary for beginners, especially if they just want to write a simple program that prints a message to the console. That’s why Java 21 introduces instance main methods, a feature that allows developers to use a more flexible and dynamic approach to initializing their applications. With instance main methods, we can write the same code as above in a much simpler way:

public class Main {
    void main() {
        // no parameter required
        System.out.println("Hello World");
    }
}
Main.java

As you can see, we can just write the main method that we want, and save this code. We can also use any access modifier (publicprotected, or default) for the main method, as long as it is not private. We don’t need to use the static modifier (static) or the parameter (String[] args) for the main method, and we can call other methods or access other fields directly from the main method.

Instance main methods are useful for beginners because they allow them to write a simple program that runs without any extra code or configuration. They also make it easier to understand the concept of objects and methods, without having to deal with the static modifier or the parameter. Instance main methods are also useful for advanced programmers who want to write more concise and expressive code, without having to follow the traditional launch protocol.



Unnamed Classes

Another thing that beginners have to learn when they start coding in Java is how to declare a class. A class is a blueprint for creating objects, and it defines the state and behavior of those objects. For example, if we want to create a class that represents a person, we have to write something like this:

public class Person {
    // state: fields that store the attributes of a person
    private String name = "Alice";
    private int age = 25;

    // behavior: methods that define the actions of a person
    public void sayHello() {
        // a custom method that prints a greeting message
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }
    
    public static void main(String[] args) {
        Person person = new Person();
        person.sayHello();
    }
}
Person.java

As you can see, there is a lot of boilerplate code that we have to write just to define a simple class. We have to specify the access modifier (public), the class name (Person), the fields (name and age), and the custom method (sayHello()). Moreover, we have to save this class in a file with the same name as the class (Person.java), and we have to put this file in a package (a folder that organizes classes into namespaces).

All of this can be overwhelming and tedious for beginners, especially if they just want to try out some basic concepts or write a small proof-of-concept program. That’s why Java 21 introduces unnamed classes, a feature that allows methods, fields, and classes to exist without explicit class declarations. With unnamed classes, we can write the same code as above in a much simpler way:

// no class declaration, no package declaration, no file name restriction
private String name = "Alice";
private int age = 25;

void sayHello() {
    System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}

void main() {
    sayHello()
}
AnyClassName.java

As you can see, we don’t need to declare a class, a package, or a file name. We can just write the fields and methods that we want, and save this code in any file with any name (for example, AnyClassName.java). Unnamed classes exist in the unnamed package and unnamed module, which are the default namespaces for Java code.

One more thing to note here is in the case of the named class Person.java, to call the sayHello() method a Person Object was required because non-static methods and fields cannot be called directly from a static context i.e. main method was static in the case of the named class due to which the non-static variables and methods cannot be called directly whereas in case of unnamed class AnyClassName.java, non-static and static fields can be called directly from the main method because the main method is not static in this case.

Unnamed classes are useful for beginners because they allow them to focus on the logic and functionality of their code, rather than the syntax and structure. They also make it easier to experiment with different ideas and test different scenarios, without having to create a lot of files and folders. Unnamed classes are also useful for advanced programmers who want to write quick scripts or prototypes, without following the usual conventions and rules of Java.



Simplified Hello World Program Using Java 21 Unnamed Classes and Instance Main Method

Post understanding the unnamed classes and instance main method this is what the simplified Hello World program looks like:

// no class declaration, no package declaration, no file name restriction

void main() {
    System.out.println("Hello World");
}
AnyClassName.java

How do you compile and run unnamed classes and instance main method?

To compile and run unnamed classes and instance main method in Java 21, you need to make use of two flags --release 21 & --enable-preview.

// Compile Java program
javac --release 21 --enable-preview YourClassName.java

// Run Java program
java --enable-preview YourClassName
CMD

In Java, the --release flag indicates the compiler’s version for code compilation, ensuring it’s compatible with the specified release.

On the other hand, the --enable-preview flag unlocks experimental features in the Java compiler, allowing developers to test and offer feedback on potentially upcoming additions.



Brainteasers

1. How does Java 21 Decide Which Main Method to Use?

Starting with Java 21, multiple signatures of the main method are supported. What if you have more than one main method in your class? How does Java 21 know which one to use?

Java 21 has a smart way of choosing the best main method for your program. It looks at the availability and the access level of each main method and follows a specific order to pick one. Here is the order:

  • If your class has a public static void main(String[] args) method, Java 21 will use that one. This is the traditional way of writing a main method, and it works with any version of Java.
  • If your class does not have a public static void main(String[] args) method, but has a static void main() method, Java 21 will use that one. This is a new way of writing a main method without the String[] parameter, and it works only with Java 21 or higher.
  • If your class does not have any static main methods, but has a void main(String[] args) instance method, Java 21 will use that one. This is another new way of writing a main method without the static keyword, and it works only with Java 21 or higher.
  • If your class does not have any static main methods or any void main(String[] args) instance methods but has a void main() instance method, Java 21 will use that one. This is the simplest way of writing a main method without the static keyword or the String[] parameter, and it works only with Java 21 or higher.

Execution Order:

1. public static void main(String[] args)
2. static void main()
3. void main(String[] args)
4. void main()

NOTE: We cannot have all 4 main methods at once in a class. We will get a compile time error in this case.

2. Can unnamed classes have user-defined constructors?

Unnamed classes can have members, including methods, fields, and static initializers, but they cannot have constructors. This is because unnamed classes are meant to be used as standalone programs or entry points to programs. Since they cannot be referred to by name, there is no need to construct instances of them directly.

3. What if we try to compile an unnamed class without the –enable-preview flag in Java 21?

If we try to compile an unnamed class without the --enable-preview flag in Java 21, we will get a compiler error. The error message will say something like:

AnyFileName.java:2: error: unnamed classes are a preview feature and are disabled by default.
CMD

4. What if we try to run an unnamed class without the –enable-preview flag in Java 21?

If we try to run an unnamed class without the --enable-preview flag in Java 21, we will get a runtime error. The error message will say something like:

Error: LinkageError occurred while loading main class AnyFileName
        java.lang.UnsupportedClassVersionError: Preview features are not enabled for AnyFileName (class file version 65.65535). Try running with '--enable-preview'
CMD

5. What if we try to compile an unnamed class without the –release flag in Java 21?

If we try to compile an unnamed class without the --release flag in Java 21, we will get a compile-time error. The error message will say something like:

error: --enable-preview must be used with either -source or --release
CMD


6. What if we try to compile an unnamed class without the –release and –enable-preview flags in Java 21?

If we try to compile an unnamed class without the --release and --enable-preview flags in Java 21, we will get a compile-time error. The error message will say something like:

AnyFileName.java:2: error: unnamed classes are a preview feature and are disabled by default.
CMD

7. What is the name of the unnamed class in the generated bytecode in Java 21?

The name of the unnamed class in the generated bytecode in Java 21 is a synthetic name generated by the compiler based on the file name of the class.

8. Can we have unnamed classes without a main method?

Unnamed classes must have a main method to be executed because they cannot be instantiated directly. The Java compiler will throw an error if an unnamed class does not have a main method.

AnyFileName.java:2: error: unnamed class does not have main method in the form of void main() or void main(String[] args)
CMD

9. Can unnamed classes in Java extend or implement other classes or interfaces?

Unnamed classes are always final, and they cannot extend other classes (except for Object) or implement interfaces. The absence of a class name restricts the use of syntax for extension and implementation.

10. Can we declare a package statement in case of unnamed classes?

An unnamed class is always a member of the unnamed package. The package statement is used to declare the package to which a class belongs. Since unnamed classes are already members of the unnamed package, there is no need to declare the package statement in them.

Another way to think about it is that unnamed classes are not visible to other classes in the program. Therefore, there is no need to declare the package to which an unnamed class belongs since other classes cannot access it anyway.

If we try to declare a package statement then we will get a compile-time error like this:

AnyFileName.java:2: error: unnamed class should not have package declaration
CMD


Things to Consider

Here are some things to consider when using unnamed classes and instance main methods in Java 21:

  • Unnamed classes are a preview feature. This means that they are not yet fully supported by the Java compiler or the Java runtime environment (JRE). It is possible that the behavior of unnamed classes may change in a future release of Java.
  • Unnamed classes cannot extend or implement other classes or interfaces. This is because unnamed classes do not have a name, and the compiler needs a name to generate the bytecode to extend or implement other classes or interfaces.
  • Unnamed classes must have a main method. This is because unnamed classes cannot be instantiated directly. The main method is the only way to execute the code in an unnamed class.
  • Avoid using them for complex programs. Unnamed classes and instance main methods are designed to simplify the learning curve for beginners and to allow quick experimentation and prototyping. They are not meant to be used for complex or modular programs that need to interact with other classes or libraries. For such programs, you should use named classes with proper declarations and references.
  • Consider man method execution order. Instance main methods have a specific execution order that you should understand. Java 21 will choose the best main method for your program based on the availability and access level of each main method. 

FAQs

What are unnamed classes in Java 21?

Unnamed classes are classes that do not have explicit names. They are a preview feature in Java 21, allowing developers to write concise and efficient code without the need for explicit class declarations.

What are instance main methods in Java 21?

Instance main methods are a new feature in Java 21 that allows you to write main methods that are not static and can take any parameters. They make it easier to write simple programs without creating a class or an object.


Valid method signatures:

1. public static void main(String[] args)
2. static void main()
3. void main(String[] args)
4. void main()

When should you use unnamed classes?

Unnamed classes are great for:

  • Quick, specific tasks: They work well for writing compact code to tackle particular jobs without complex class structures.
  • Trying out new ideas: They’re handy for experimenting with new code or testing concepts.
  • Learning: They make code examples and tutorials easier to follow for educational purposes.

When should you use instance main methods?

You should use instance main methods when you want to write a quick and easy program that does not need a class or an object. For example, if you want to print something to the console, calculate something, or test some code. Instance main methods are also useful for learning Java basics without worrying about the static keyword or the String[] parameter.

Conclusion

In this blog post, we have learned about two new features of Java 21: unnamed classes and instance main methods. These features are designed to simplify the learning curve for beginners and allow them to bootstrap a class with minimal syntax. They are also useful for advanced programmers who want to write quick scripts or prototypes, without following the usual conventions and rules of Java.

Learn More

#

Interested in learning more?

Check out our blog on how to use compute methods for Cleaner Maps

Top Picks for Learning Java

Explore the recommended Java books tailored for learners at different levels, from beginners to advanced programmers.

Disclaimer: The products featured or recommended on this site are affiliated. If you purchase these products through the provided links, I may earn a commission at no additional cost to you.

1
Java: The Complete Reference
13th Edition

Java: The Complete Reference

  • All Levels Covered: Designed for novice, intermediate, and professional programmers alike
  • Accessible Source Code: Source code for all examples and projects are available for download
  • Clear Writing Style: Written in the clear, uncompromising style Herb Schildt is famous for
2
Head First Java: A Brain-Friendly Guide

Head First Java: A Brain-Friendly Guide

  • Engaging Learning: It uses a fun approach to teach Java and object-oriented programming.
  • Comprehensive Content: Covers Java's basics and advanced topics like lambdas and GUIs.
  • Interactive Learning: The book's visuals and engaging style make learning Java more enjoyable.
3
Modern Java in Action: Lambdas, streams, functional and reactive programming
2nd Edition

Modern Java in Action: Lambdas, streams, functional and reactive programming

  • Latest Java Features: Explores modern Java functionalities from version 8 and beyond, like streams, modules, and concurrency.
  • Real-world Applications: Demonstrates how to use these new features practically, enhancing understanding and coding skills.
  • Developer-Friendly: Tailored for Java developers already familiar with core Java, making it accessible for advancing their expertise.
4
Java For Dummies
8th Edition

Java For Dummies

  • Java Essentials: Learn fundamental Java programming through easy tutorials and practical tips in the latest edition of the For Dummies series.
  • Programming Basics: Gain control over program flow, master classes, objects, and methods, and explore functional programming features.
  • Updated Coverage: Covers Java 17, the latest long-term support release, including the new 'switch' statement syntax, making it perfect for beginners or those wanting to brush up their skills.

Add a Comment

Your email address will not be published.