我想将类的构造函数拆分成多个部分。但是我有一个问题...
是否可以在构造函数内部调用的方法中初始化最终值?它必须直接在构造函数中初始化吗?
这...
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/