Compile time error “final variable is not initialized”

余生长醉 提交于 2019-12-12 03:48:47

问题


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.


回答1:


final int 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);
    }

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.

How to resolve this?

As you said, either you have to comment this constructor (or) assign i value inside this constructor as you did in other constructor.




回答2:


   O(int j){
        this(); // <----- you can add this line. 
        j=20;
        System.out.println(j);
    }



回答3:


A final variable has to be initialized on declaration or assigned to a value in the constructors body. If you don't initialize the final variable you get a compiler error.

If you invoke the second constructor the variable never gets assigned to a value.




回答4:


"i" is a instance final variable thus we need to initialize it in each and every constructor i define.



来源:https://stackoverflow.com/questions/13052571/compile-time-error-final-variable-is-not-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!