4
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);
    }
}

在 Eclipse 中尝试上面的代码时,eclipse 显示“对变量 j 的赋值没有效果”显示为在构造函数中初始化变量“j”。

请告诉我为什么变量 j 没有效果。

4

6 回答 6

6

该参数j正在遮蔽类成员j。尝试按如下方式更改您的代码:

public A(int j)
{
     A.j = j;
}
于 2012-05-19T05:59:30.583 回答
4

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).

于 2012-05-19T06:01:46.397 回答
3

将变量分配给自身具有什么都不做的净值。

于 2012-05-19T05:40:21.473 回答
0

因为final变量只能被赋值一次,这意味着在JVM执行static变量期间一次,而构造函数是在每次创建对象时执行的。

于 2012-05-19T05:39:27.007 回答
0

您可能想阅读一下这个。它说在某些情况下,生成的警告是不正确的,就像你的情况一样。

于 2012-05-19T05:49:20.157 回答
0

使用this.j = j;

使用j = j时,两个“j”是一样的,只是构造函数的参数,而不是A类的字段。如果要A的字段j,请使用this.j

于 2012-05-19T07:10:02.993 回答