java - 将构造函数方法拆分为多个部分 - 最终值的问题

标签 java constructor final

我想将类的构造函数拆分成多个部分。但是我有一个问题...

是否可以在构造函数内部调用的方法中初始化最终值?它必须直接在构造函数中初始化吗?

这...

import java.util.Scanner;

public final class A
{
    private final int L;
    private final int D;
    private final int N;

    public A()
    {
        Scanner scanner = new Scanner(System.in);
        this.getFirstLine(scanner);

        /* the rest of the constructor method */
    }

    private void getFirstLine(Scanner scanner)
    {
        this.L = scanner.nextInt();
        this.D = scanner.nextInt();
        this.N = scanner.nextInt();
    }
}

给我的错误类似于The final field A.L cannot be assigned

所以它被视为一个作业?是吗?

有没有办法拆分构造函数来实现我想要的?

提前致谢。

最佳答案

您不能根据 Java Language Spec 执行此操作:

A blank final instance variable must be definitely assigned (§16.9) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs.

您可以在构造函数中执行此操作,因为编译器可以保证每个实例只调用一次构造函数。下面的代码编译。我刚刚验证了它:

import java.util.Scanner;

public final class A
{
    private final int L;
    private final int D;
    private final int N;

    public A()
    {
        Scanner scanner = new Scanner(System.in);
        this.L = scanner.nextInt();
        this.D = scanner.nextInt();
        this.N = scanner.nextInt();

        /* the rest of the constructor method */
    }
}

您不能在非构造函数方法中分配最终变量,因为不能保证每个实例只调用一次。

关于java - 将构造函数方法拆分为多个部分 - 最终值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5359683/

相关文章:

java - 如何通过Java代码运行命令

java - Android 单元测试不会使用正确的应用程序类

java - 为什么final可以在构造函数中初始化?

java - 如果不会重新分配,我是否应该将所有形式参数设置为final?

java - 更改以前的 ListView 中的 ListView 项目

java - 编码 SOAP 消息时避免重复的命名空间

c++:引用父级的成员

具有构造函数的类的 C++ vector

c# - 带参数的静态资源构造器

c++ - 纯虚最终函数 : legal in C++11