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.
I have understanding of JAVA but i am confused in this code.
You have defined
iasfinal. You can assign values to final variables only in constructors.Here you are not assigning value for
i. If someone uses this constructor (constructor with parameter) to create an object,ivalue won’t be assigned.How to resolve this?
As you said, either you have to comment this constructor (or) assign
ivalue inside this constructor as you did in other constructor.