public class A{
public static final int j;
public static int x;
static{
j=9;
}
public A(int j)
{
j = j;
}
protected void print()
{
System.out.println(j);
}
}
When trying code above in the eclipse, eclipse shows that "The assignment to variable j has no effect" is shown for intializing the vaiable "j" in the constructor.
Please do tell me why the variable j has no effect.
The parameter j
is shadowing the class member j
. Try to change your code as follows:
public A(int j)
{
A.j = j;
}
The class variable j (static final int j) is assigned the value 9 in the static block. That is all valid.
In the constructor, the parameter j, is assigned to itself and that has no effect. The alternative (and I suspect what you meant) is:
public A(int j)
{
A.j = j;
}
Here the parameter j is assigned to the class variable j. However, Java will complain here as the class variable is final. If you remove the final keyword, this will of course work as well. However, now it gets interesting:
The value of class j, will be 9 as long as no instance of class A is created. The moment an instance of the class is created through the new operator, all instances of the class A will have the same value for the class variable j (dependant on what you sent the constructor).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With