What is the problem with parameters in the constructor of a Class in Java?

Viewed 308

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;
    }
}
3 Answers

In

X(int i)
{
    i = 20;
}

The local variable i (the argument of the constructor) hides the instance variable i. Therefore i = 20; modifies the local variable, not the final instance variable of the same name, which remains uninitialized.

You can avoid this issue with:

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

or

X(int i)
{
    this.i = i;
}
class X
{ 
    final int i;
    X()
    {
        i = 0;
    }

What you are saying above is basically that your i is equal to 0 if no parameters are given. It is the same as saying i=0or this.i=0. Same thing as there is only one i, so thisis not really needed.

On the other side, below, there are 2 instances of i, so you need to make sure Java knows which one is which one. In this case, imagine you wanted to equal the iof X, to the ipassed as a parameter: this.i=i;is what you would be looking for. "My i of the class should be the i passed as a parameter.

So in this case, if your constructor receives an int, it should give YOUR ithe value 20. If your parameter was j, as jis not defined in your class, it takes the ias the iof your class. But having 2 i, you should make sure which one is which one!

 X(int i)//need to keep other than i
    {
//the i of my class should be 20. remember! this.i=i if you want the i of your class to be equal to the parameter passed i
            this.i = 20;
        }
    }

In the code above you're never initializing the variable final int i which should either be done when declaring this variable or in the constructors of your class, even though you're doing i = 20; you're refering to the int i which is part of the parameters of that method.

If you wanted to change the value of final int i and have a parameter named i in your method, you have to call this.i = 20; and it will be fixed.

Related