首页 > 解决方案 > What is the problem with parameters in the constructor of a Class in Java?

问题描述

In this code if I keep int i in the parameterized constructor, it throws an error. If anything other than int i is working fine.

Example: int j works fine. What is the reason for this error, please enlighten my knowledge.

//this program throws an error
class X
{ 
    final int i;
    X()
    {
        i = 0;
    }
    X(int i)//need to keep other than i
    {
        i = 20;
    }
}

//this program works fine
class X
{ 
    final int i;
    X()
    {
        i = 0;
    }   
    X(int j)
    {
        i = 20;
    }
}

标签: javaconstructorfinal

解决方案


X(int i)
{
    i = 20;
}

局部变量i(构造函数的参数)隐藏了实例变量i。因此i = 20;修改的是局部变量,而不是final同名的实例变量,它保持未初始化。

您可以通过以下方式避免此问题:

X(int i)
{
    this.i = 20;
}

或者

X(int i)
{
    this.i = i;
}

推荐阅读