简体   繁体   English

编译时错误“最终变量未初始化”

[英]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. 即使错误发生在我写参数化缺点的那一行。

I have understanding of JAVA but i am confused in this code. 我对JAVA有所了解,但是我对这段代码感到困惑。

final int i;

You have defined i as final . 您已将i定义为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 . 在这里,您没有为i赋值。 If someone uses this constructor (constructor with parameter) to create an object, i value won't be assigned. 如果有人使用此构造函数(带参数的构造函数)创建对象,则不会分配i值。

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. 如您所说,您必须注释该构造函数(或)像在其他构造函数中一样在此构造函数中分配i值。

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

A final variable has to be initialized on declaration or assigned to a value in the constructors body . final变量必须在声明时初始化,或分配给构造函数主体中的值。 If you don't initialize the final variable you get a compiler error. 如果不初始化final变量,则会出现编译器错误。

If you invoke the second constructor the variable never gets assigned to a value. 如果调用第二个构造函数,则变量永远不会赋值。

“ i”是实例最终变量,因此我们需要在我定义的每个构造函数中对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM