编译时错误“最终变量未初始化”。 [英] Compile time error "final variable is not initialized"
问题描述
我遇到一个问题,在尝试一些代码片段时遇到了一个代码
I have an issue, while trying few code snippets i came across a code
class O
{
final int i;
O()
{
i=10;
}
O(int j)// error here as THE BLANK FINAL FIELD i IS NOT INITIALIZED
{
j=20;
System.out.println(j);
}
}
class Manager3
{
public static void main(final String[] args)
{
O n1=new O();
//O n2=new O(10);
//n1.i=20;
//System.out.println(j1.i);
}
}
但是如果我用参数注释构造函数,我不会出现任何错误。
but if i comment the constructor with parameter i do not get any errors.
我的问题是为什么当我将构造函数都放入代码时为什么会出现此编译时错误,以及为什么在删除参数化构造函数时没有出现任何错误? 。
My question is why am i getting this compile time error when i put both the constructor in code and why i dont get any error when i remove parameterized constructor.
我知道我们必须初始化我的最终变量,但是我正在构造函数中对其进行初始化,因此如果我编写此代码:-
I know that we have to initialize my final variable, but i am initializing it in constructor thus if i write this code :-
class O
{
final int i;
O()
{
i=10;
}
}
class Manager3
{
public static void main(final String[] args)
{
O n1=new O();
}
}
这一切工作正常且代码合理
every this is working fine and code is compiling.
我的问题是,如果我引入另一个构造函数,会出现什么问题。
My question is what is the issue if i introduce another constructor. Even the error is at the line where i write parameterized cons.
我对JAVA有所了解,但是我对这段代码感到困惑。
I have understanding of JAVA but i am confused in this code.
推荐答案
final int i;
您已将 i
定义为最终
。您只能在构造函数中将值分配给最终变量。
You have defined i
as final
. You can assign values to final variables only in constructors.
O(int j)// error here as THE BLANK FINAL FIELD i IS NOT INITIALIZED
{
j=20;
System.out.println(j);
}
在这里,您没有为 i赋值
。如果有人使用此构造函数(带参数的构造函数)创建对象,则不会分配 i
值。
Here you are not assigning value for i
. If someone uses this constructor (constructor with parameter) to create an object, i
value won't be assigned.
如何解决此问题?
正如您所说,您必须注释此构造函数(或)分配 i
值,就像在其他构造函数中一样。
As you said, either you have to comment this constructor (or) assign i
value inside this constructor as you did in other constructor.
这篇关于编译时错误“最终变量未初始化”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!