Unnamed Classes and Instance Main Methods in Java 21 – Java 中的未命名类和实例主方法 21

最后修改: 2023年 10月 3日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.导言

Java 21 is here, and among the new features, we can see how Java is becoming increasingly accessible for beginners with the unnamed classes and instance main methods. The introductions of these are crucial steps forward in making Java a more beginner-friendly programming language.

Java 21 来了,在新功能中,我们可以看到 Java 通过未命名类和实例主方法变得越来越便于初学者使用。这些功能的引入是使 Java 成为更适合初学者的编程语言的关键步骤。

In this tutorial, we’ll explore these new features and understand how they make the learning curve smoother for students.

在本教程中,我们将探索这些新功能,了解它们如何让学生的学习曲线更加顺畅。

2. Writing a Basic Java Program

2. 编写基本 Java 程序

Traditionally, for beginners, writing their first Java program was a little more complicated than in other programming languages. A basic Java program required the declaration of a public class. This class encloses a public static void main(String[] args) method, serving as the entry point of the program.

传统上,对于初学者来说,编写第一个 Java 程序要比其他编程语言复杂一些。一个基本的 Java 程序需要声明一个 public 类。该类包含一个 public static void main(String[] args) 方法,作为程序的入口点。

All of this is just to write a “Hello world” in the console:

所有这一切都只是为了在控制台中写下“Hello world”

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

Java 21 greatly simplifies the way we can write a simple program:

Java 21 大大简化了我们编写简单程序的方法:

void main() {
    System.out.println("Hello, World!");
}

We’ll go into more detail about how we achieved this syntax simplification using the new features.

我们将详细介绍如何利用新功能实现语法简化。

3. Instance Main Methods

3. 实例主方法

The introduction of instance main() methods allows developers to utilize a more dynamic approach to initializing their applications.

实例 main() 方法的引入使开发人员能够使用更动态的方法来初始化应用程序。

3.1. Understanding Instance Main Methods

3.1.了解实例主方法

This has changed the way Java programs declare their entry points. In fact, Java earlier required the presence of a static main() method with a String[] parameter in the public class, as we saw in the previous section.

这改变了 Java 程序声明其入口点的方式。事实上,Java 早期要求在 public 类中存在一个 static ain() 方法,其中包含一个 String[] 参数,正如我们在上一节中所看到的。

This new protocol is more lenient. It enables the use of main() methods with varied access levels: public, protected, or default (package).

新协议更加宽松。它允许使用不同 访问级别main() 方法:公开受保护或默认(包)。

Also, it doesn’t require the methods to be static or to have a String[] parameter:

此外,它不要求方法必须是静态的,也不要求方法必须有一个String[]参数。

class HelloWorld {
    void main() {
        System.out.println("Hello, World!");
    }
}

3.2. Choosing a Launch Protocol

3.2.选择发射协议

The refined launch protocol chooses automatically a starting point for our program, taking into account both availability and access level.

考虑到可用性和访问级别,完善后的发射协议自动选择了我们计划的起点。

Instance main() methods should always have a non-private access level. Moreover, the launch protocol follows a specific order to decide which method to use:

实例 ain() 方法应始终具有非私有访问级别。此外,启动协议遵循特定的顺序来决定使用哪种方法:

  1.  a static void main(String[] args) method declared in the launched class
  2.  a static void main() method declared in the launched class
  3.  a void main(String[] args) instance method declared in the launched class or inherited from a superclass
  4.  a void main() instance method

When a class declares an instance main() method and inherits a standard static main() method, the system invokes the instance main() method. In such cases, the JVM issues a warning at runtime.

当类声明了实例 ain() 方法并继承了标准 static ain() 方法时,系统将调用实例 ain() 方法。在这种情况下,JVM 会在运行时发出警告。

For example, let’s suppose we have a superclass HelloWorldSuper, that implements a long-established main() method:

例如,假设我们有一个超类HelloWorldSuper,它实现了一个早已确立的ain()方法:

public class HelloWorldSuper {
    public static void main(String[] args) {
        System.out.println("Hello from the superclass");
    }
}

This superclass is extended by a HelloWorldChild class:

该超类由 HelloWorldChild 类扩展:

public class HelloWorldChild extends HelloWorldSuper {
    void main() {
        System.out.println("Hello, World!");
    }
}

Let’s compile the superclass and run the child using the — source 21 and –enable-preview flags:

让我们编译超类,并使用 – source 21-enable-preview 标记运行子类:

javac --source 21 --enable-preview HelloWorldSuper.java
java --source 21 --enable-preview HelloWorldChild

We’ll get the following output in the console:

我们将在控制台中得到以下输出:

WARNING: "void HelloWorldChild.main()" chosen over "public static void HelloWorldSuper.main(java.lang.String[])"
Hello, World!

We can see how the JVM warns us that we have two possible entry points in our program.

我们可以看到 JVM 是如何警告我们程序中有两个可能的入口点的。

4. Unnamed Classes

4.无名班级

Unnamed classes are a significant feature designed to simplify the learning curve for beginners. It allows methods, fields, and classes to exist without explicit class declarations.

未命名类是一项重要功能,旨在简化初学者的学习曲线。它允许方法、字段和类在没有显式类声明的情况下存在。

Typically, in Java, every class exists within a package and every package within a module. Unnamed classes, however, exist in the unnamed package and unnamed module. They are final and can only extend the Object class without implementing any interface.

通常,在 Java 中,每个类都存在于一个包中,每个包都存在于一个模块中。然而,未命名的类存在于未命名的包和未命名的模块中。它们是最终类,只能扩展对象类,而不能实现任何接口。

Given all this, we can declare the main() method without declaring the class explicitly in the code:

综上所述,我们可以声明 main() 方法,而无需在代码中明确声明类:

void main() { 
    System.out.println("Hello, World!");
}

Using these two new features, we managed to turn the program into a very simple one that can be much easier to understand by any person who starts programming in Java.

利用这两项新功能,我们成功地将程序变成了一个非常简单的程序,任何开始使用 Java 编程的人都可以更容易地理解它。

An unnamed class is almost exactly like an explicitly declared class. Other methods or variables are interpreted as members of the unnamed class, so we can add them to our class:

未命名类几乎与明确声明的类完全相同。其他方法或变量被解释为未命名类的成员,因此我们可以将它们添加到我们的类中:

private String getMessage() {
    return "Hello, World!";
}
void main() {
    System.out.println(getMessage());
}

Despite their simplicity and flexibility, unnamed classes have inherent limitations.

尽管未命名类简单灵活,但也有其固有的局限性。

Direct constructions or references by name are impossible, and they don’t define any API accessible from other classes. This inaccessibility also causes the Javadoc tool to falter when generating API documentation for such classes. However, future Java releases may adjust and enhance these behaviors.

直接构造或名称引用是不可能的,而且它们没有定义任何可从其他类访问的 API。这种不可访问性还会导致 Javadoc 工具在为此类类生成 API 文档时出现问题。不过,未来的 Java 版本可能会调整和增强这些行为。

5. Conclusion

5.结论

In this article, we learned that Java 21, with the introduction of unnamed classes and instance main() methods, has made significant progress in enhancing user experience, especially for those at the beginning of their programming journey.

在这篇文章中,我们了解到 Java 21 引入了未命名类和实例 main() 方法,在增强用户体验方面取得了重大进展,尤其是对于那些刚开始编程的人来说。

By simplifying the structural aspects of programming, these features allow novices to focus on logical thinking and problem-solving more quickly.

通过简化编程的结构方面,这些功能可以让新手更快地专注于逻辑思维和解决问题。

As always, the source code is available over on GitHub.

与往常一样,源代码可在 GitHub 上获取