在Java中的构造函数之前初始化最终变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/677595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize final variable before constructor in Java
提问by Tobias
Is there a solution to use a final variable in a Java constructor? The problem is that if I initialize a final field like:
是否有在 Java 构造函数中使用 final 变量的解决方案?问题是,如果我初始化一个最终字段,如:
private final String name = "a name";
then I cannot use it in the constructor. Java first runs the constructor and then the fields. Is there a solution that allows me to access the final field in the constructor?
那么我不能在构造函数中使用它。Java 首先运行构造函数,然后运行字段。是否有解决方案允许我访问构造函数中的最终字段?
采纳答案by Johannes Weiss
I do not really understand your question. That
我不太明白你的问题。那
public class Test3 {
private final String test = "test123";
public Test3() {
System.out.println("Test = "+test);
}
public static void main(String[] args) {
Test3 t = new Test3();
}
}
executes as follows:
执行如下:
$ javac Test3.java && java Test3
Test = test123
回答by Hank Gay
Do the initialization in the constructor, e.g.,
在构造函数中进行初始化,例如,
private final String name;
private YourObj() {
name = "a name";
}
Of course, if you actually know the value at variable declaration time, it makes more sense to make it a constant, e.g.,
当然,如果你真的知道变量声明时的值,让它成为一个常量更有意义,例如,
private static final String NAME = "a name";
回答by Outlaw Programmer
In this case, you can mark the field as 'static' also.
在这种情况下,您也可以将该字段标记为“静态”。
回答by Adam Jaskiewicz
In that case, you might as well make it static, too. And Java convention is to name such constants in ALL_CAPS.
在这种情况下,您也可以将其设为静态。Java 约定是在 ALL_CAPS 中命名此类常量。
回答by daanish.rumani
private static final String name = getName();
where getName()is a static function that gets you the name.
其中getName()是一个静态函数,用于获取名称。
回答by sfossen
Marking it static, will allow you to use it in the constructor, but since you made it final, it can not be changed.
将其标记为静态,将允许您在构造函数中使用它,但由于您将其设为 final,因此无法更改。
private static final String name = "a_name";
is is possible to use a static init block as well.
也可以使用静态 init 块。
private static final String name;
static { name = "a_name"; }
If you are trying to modify the value in the constructor, then you can't assign a default value or you have to make it not final.
如果您尝试修改构造函数中的值,则不能分配默认值或必须使其不是最终值。
private String name = "a_name";
Foo( String name )
{
this.name = name;
}
or
或者
private final String name;
Foo( String name )
{
if( s == null )
this.name = "a_name";
else
this.name = name;
}
回答by soulmerge
I cannot use it in the constructor, while java first runs the constructor an then the fields...
我不能在构造函数中使用它,而 java 首先运行构造函数然后是字段......
This is not correct, fields are evaluated first, otherwise you couldn't access any default values of members in your constructors, since they would not be initialized. This doeswork:
这是不正确的,首先评估字段,否则您无法访问构造函数中成员的任何默认值,因为它们不会被初始化。这确实有效:
public class A {
protected int member = 1;
public A() {
System.out.println(member);
}
}
The keyword finalmerely marks the member constant, it is treated as any other member otherwise.
关键字final仅标记成员常量,否则将被视为任何其他成员。
EDIT: Are you trying to setthe value in the constructor? That wouldn't work, since the member is immutable if defined as final.
编辑:您是否尝试在构造函数中设置值?这是行不通的,因为如果定义为最终成员,则该成员是不可变的。
回答by Joachim Sauer
Another possiblity is to initialize the field in an instance initializer blocK:
另一种可能性是在实例初始化块中初始化字段:
public class Foo {
final String bar;
{
System.out.println("initializing bar");
bar = "created at " + System.currentTimeMillis();
}
public Foo() {
System.out.println("in constructor. bar=" + bar);
}
public static void main(String[] args) {
new Foo();
}
}
回答by Steve Gelman
We're getting away from the question.
我们正在远离这个问题。
Yes, you can use a private final
variable. For example:
是的,您可以使用private final
变量。例如:
public class Account {
private final String accountNumber;
private final String routingNumber;
public Account(String accountNumber, String routingNumber) {
this.accountNumber = accountNumber;
this.routingNumber = routingNumber;
}
}
What this means is that the Account class has a dependency on the two Strings, account and routing numbers. The values of these class attributes MUST be set when the Account class is constructed, and these number cannot be changed without creating a new class.
这意味着 Account 类依赖于两个字符串,即帐户和路由号码。这些类属性的值必须在构建 Account 类时设置,并且这些数字不能在不创建新类的情况下更改。
The 'final' modifier here makes the attributes immutable.
这里的“final”修饰符使属性不可变。