声明后是否可以初始化最终变量?
这是否可能,很少有人认为它可能,我也在这里看到它 链接..但是当我亲自尝试时,它给了我编译时错误..
我的意思是这个,
Class A{
private final String data;
public A(){
data = "new string";
}
}
提前感谢..
Is this even possible, few argue its possible and i saw it here too link.. but when i personally tried it gives me compile time errors..
i mean this,
Class A{
private final String data;
public A(){
data = "new string";
}
}
Thanks in advance..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,这是可能的。类是用小写 c 编写的。否则你的代码完全没问题(除了标识):
Yes, it is possible. Class is written with small case c. Otherwise your code is perfectly fine (except for identation):
您可以在声明后初始化最终实例变量。
堵塞。
您发布的代码的问题是大写的
C
。正如鲍里斯指出的那样,它应该是class
。You can initialize a final instance variable after declaration.
block.
The problem with the code you've posted is the uppercase
C
. It should have beenclass
as Boris pointed out.您可能有多个构造函数,在这种情况下,您必须在每个构造函数中初始化最终实例字段。
It is likely that you are having more than one constructor, in that case you must initialize the final instance field in each of those constructors.
就像鲍里斯建议的那样,代码很好。但您不能做的是为最终变量数据分配第二个值。
data = "another string";
将无法编译,因为 data 是最终的,因此其值在初始化后无法更改。Like Boris suggested the code is fine. What you can not do though, would be to assign a second value to the final variable data.
data = "another string";
will not compile, since data is final and thus its value can not be changed after the initialization.