无法为最终变量“名称"分配值 [英] Cannot assign a value to final variable 'name'
本文介绍了无法为最终变量“名称"分配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么 Java
不允许我间接初始化最终变量?我不明白为什么它不起作用,我的意思是该方法将始终运行,因此,如果直接或通过方法进行初始化,会产生什么不同?
Why isn't Java
allowing me to initialize final variables indirectly? I don't see why it shouldn't work, I mean the method will always run so what difference does it make if initialized directly or via method?
此代码有效:
package com.company;
public class Person {
private final String name;
public Person() {
name = "bob";
}
}
这不是.(即使我摆脱了IO代码并硬编码分配给name的值)
This one doesn't. (even if I get rid of IO code and hardcode the value assigned to name)
package com.company;
import java.util.Scanner;
public class Person {
private final String name;
public Person() {
askName();
}
public void askName() {
Scanner scanner = new Scanner(System.in);
name = scanner.nextLine();
}
}
推荐答案
final
字段必须在构造函数中设置.您可以执行以下操作.
final
fields must be set in the constructor. What you can do is the following.
import java.util.Scanner;
public class Person {
private final String name;
public Person() {
name = askName();
}
public static String askName() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
}
但是,更好的选择可能会注入您所需的值.
However, a better option is likely to inject the value you need.
import java.util.Scanner;
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public static Person askName() {
Scanner scanner = new Scanner(System.in);
return new Person(scanner.nextLine());
}
}
这篇关于无法为最终变量“名称"分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文