Constructor Specification in Java – Java中的构造函数规范

最后修改: 2022年 1月 23日

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

1. Overview

1.概述

In this tutorial, we’ll learn how Java deals with constructors and review some rules related to them from the Java Language Specification.

在本教程中,我们将学习Java如何处理结构体,并回顾Java语言规范中与它们相关的一些规则。

2. Constructor Declarations

2.构造函数声明

In Java, every class must have a constructor. Its structure looks similar to a method, but it has different purposes.

在Java中,每个类都必须有一个构造函数。它的结构看起来与方法类似,但它有不同的目的。

Let’s see the specification of the constructor:

让我们看看构造函数的规范。

<Constructor Modifiers> <Constructor Declarator> [Throws Clause] <Constructor Body>

Let’s look at each piece separately.

让我们分别看一下每一块。

2.1. Constructor Modifiers

2.1. 构造函数修改器

Constructor declarations begin with access modifiers: They can be public, private, protected, or package access, based on other access modifiers.

构造函数声明以访问修饰符开始。它们可以是publicprivateprotected,或基于其他访问修饰符的包访问。

To prevent compilation errors, constructor declarations may not have more than one private, protected, or public access modifier.

为了防止编译错误,构造函数声明不得有一个以上的privateprotectedpublic访问修饰符。

Unlike methods, a constructor can’t be abstract, static, final, native, or synchronized:

与方法不同,构造函数不能是抽象静态最终、本地或同步

  • It isn’t necessary to declare a constructor final because they are not class members and they do not inherit.
  • The abstraction is unnecessary because we must implement the constructors.
  • A static constructor is not required since each constructor is called with an object.
  • An object under construction should not be synchronized since it would lock the object while it is being constructed, which is not normally made available to other threads until all the constructors have completed their work.
  • There are no native constructors in Java because this is a language design decision that is meant to make sure that superclass constructors are always invoked during object creation.

2.2. Constructor Declarator

2.2.构造函数声明器

Let’s examine the syntax of a Constructor Declarator:

让我们来看看构造函数声明器的语法。

Constrcutor Name (Parameter List)

There must be a match between the constructor name in the declarator and the name of the class that contains the constructor declaration, or else a compile-time error will occur.

声明器中的构造函数名称和包含构造函数声明的类的名称之间必须匹配,否则会发生编译时错误。

2.3. Throws Clause

2.3.抛出条款

The structure and behavior of throws clauses for methods and constructors are both the same.

方法和构造函数的throws条款的结构和行为都是一样的。

2.4. Constructor Body

2.4.构造函数主体

The syntax of a constructor body is:

构造函数体的语法是:。

Constructor Body: { [Explicit Constructor Invocation] [Block Statements] }

We can explicitly call another constructor of the same class or a direct superclass as the first command in a constructor body. The direct or indirect invocation of the same constructor is not allowed.

我们可以明确地调用同一类或直接超类的另一个构造函数,作为构造函数体的第一个命令。不允许直接或间接调用同一个构造函数。

3. Explicit Constructor Invocations

3.明确的构造函数调用

We can divide the invocations of constructors into two types:

我们可以把构造函数的调用分为两种类型。

  • Alternate constructor invocations begin with the keyword this. They are used to invoke alternate constructors of the same class.
  • Superclass constructor invocations begin with the keyword super.

Let’s look at an example of how we can use this and super keywords to invoke another constructor:

让我们看一个例子,看看我们如何使用thissuper关键字来调用另一个构造函数。

class Person {
    String name;

    public Person() {
        this("Arash");   //ExplicitConstructorInvocation
    }

    public Person(String name){
        this.name = name;
    }
}

Here, the first constructor of Employee invokes the constructor of its superclass Person, passing along the id:

这里,Employee的第一个构造函数调用了它的超类Person的构造函数,同时传递了id。

class Person {
    int id;
    public Person(int id) {
        this.id = id;
    }
}

class Employee extends Person {
    String name;
    public Employee(int id) {
        super(id);
    }
    public Employee(int id, String name) {
        super(id);
        this.name = name;
    }
}

4. Rules of Constructor Invocation

4.构造函数的调用规则

4.1. this or super Must Be the First Statement in the Constructor

4.1.thissuper必须是构造函数中的第一个语句

Whenever we call a constructor, it must call the constructor of its base class. In addition, you can call another constructor within the class. Java enforces this rule by making the first call in a constructor be to this or super.

每当我们调用一个构造函数时,它必须调用其基类的构造函数。此外,你可以在该类中调用另一个构造函数。Java通过使构造函数中的第一个调用指向thissuper来执行这一规则。

Let’s take a look at an example:

我们来看看一个例子。

class Person {
    Person() {
        //
    }
}
class Employee extends Person {
    Employee() {
        // 
    }
}

Here’s an example of constructor compilation:

下面是一个构造函数编译的例子。

.class Employee
.super Person
; A constructor taking no arguments
.method <init>()V
aload_0
invokespecial Person/<init>()V
return
.end method

Constructor compilation is similar to compiling any other method except that the generated method has the name <init>. One of the requirements for verifying an <init> method is that the call to the superclass constructor (or to some other constructor in the current class) must be the first step in the method.

构造函数的编译与其他方法的编译类似,只是生成的方法名称为<init>。验证<init>方法的要求之一是,对超类构造函数(或当前类中的其他构造函数)的调用必须是该方法的第一个步骤。

As we can see above, the Person class must call its superclass constructor, and so on up to java.lang.Object.

正如我们在上面看到的,Person类必须调用它的超类构造函数,以此类推,直至java.lang.Object。

When classes must call their superclass constructor, it ensures that they will never be used without proper initialization. The JVM’s security depends on this, as some methods will not work until the class has been initialized.

当类必须调用它们的超类构造函数时,它可以确保它们在没有适当初始化的情况下绝不会被使用。JVM的安全性取决于此,因为在类被初始化之前,一些方法将无法工作。

4.2. Don’t Use Both this and super in the Constructor

4.2.在构造函数中不要同时使用 thissuper

Imagine if we could use this and super together in the constructor body.

想象一下,如果我们能在构造函数体中一起使用thissuper

Let’s see what would happen through an example:

让我们通过一个例子看看会发生什么。

class Person {
    String name;
    public Person() {
        this("Arash");
    }

    public Person(String name) {
        this.name = name;
    }
}

class Employee extends Person {
    int id;
    public Employee() {
        super();
    }

    public Employee(String name) {
        super(name);
    }

    public Employee(int id) {
        this();
        super("John"); // syntax error
        this.id = id;
    }

    public static void main(String[] args) {
        new Employee(100);
    }
}

We cannot execute the above code because a compile-time error will appear. The Java compiler has its logical explanation, of course.

我们不能执行上述代码,因为会出现一个编译时错误。当然,Java编译器有其合理的解释。

Let’s take a look at the constructor invocation sequence:

让我们来看看构造函数的调用顺序。

constructor-2

The Java compiler does not permit compilation of this program because initialization is unclear.

Java编译器不允许编译这个程序,因为初始化不明确。

4.3. Recursive Constructor Invocation

4.3.递归构造函数调用

The compiler will throw an error if a constructor calls itself. For example, in the following Java code, the compiler will throw an error because we’re trying to call the same constructor within the constructor:

如果一个构造函数调用自己,编译器将抛出一个错误。例如,在下面的Java代码中,编译器将抛出一个错误,因为我们试图在构造函数中调用同一个构造函数。

public class RecursiveConstructorInvocation {
    public RecursiveConstructorInvocation() {
        this();
    }
}

Despite the Java compiler’s restriction, we can compile the program by changing the code slightly, but we will encounter a stack overflow this way:

尽管Java编译器的限制,我们可以通过稍微改变代码来编译该程序,但这样做会遇到堆栈溢出。

public class RecursiveConstructorInvocation {
    public RecursiveConstructorInvocation() {
        RecursiveConstructorInvocation rci = new RecursiveConstructorInvocation();
    }

    public static void main(String[] args) {
        new RecursiveConstructorInvocation();
    }
}

We’ve created a RecursiveConstructorInvocation object that is initialized by calling the constructor. The constructor then creates another RecursiveConstructorInvocation object that is initialized by calling the constructor again until the stack overflows.

我们创建了一个RecursiveConstructorInvocation对象,通过调用构造函数进行初始化。然后构造函数创建了另一个递归构造函数调用对象,通过再次调用构造函数进行初始化,直到堆栈溢出。

Now, let’s see the output:

现在,让我们看看输出结果。

Exception in thread "main" java.lang.StackOverflowError
	at org.example.RecursiveConstructorInvocation.<init>(RecursiveConstructorInvocation.java:29)
	at org.example.RecursiveConstructorInvocation.<init>(RecursiveConstructorInvocation.java:29)
	at org.example.RecursiveConstructorInvocation.<init>(RecursiveConstructorInvocation.java:29)
//...

5. Conclusion

5.总结

In this tutorial, we discussed the specification of constructors in Java and reviewed some rules for understanding the invocation of constructors in a class and superclass.

在本教程中,我们讨论了Java中构造函数的规范,并回顾了理解类和超类中构造函数调用的一些规则。

As always, code samples can be found over on GitHub.

一如既往,代码样本可以在GitHub上找到over