如果您运行以下代码片段,您将获得最终变量 X 和 Y 的输出。
X = 1 Y = 2
X = 4 Y = 5
从输出中可以明显看出,最终变量已被重新分配。我想知道,它是否违反了 Java Final 变量的合同。有什么想法吗?
public class FinalVariablesTest {
private final int x;
private final int y;
public FinalVariablesTest() {
this.x = 1;
this.y = 2;
}
public FinalVariablesTest(int xValue, int yValue) {
this.x = xValue;
this.y = yValue;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public static void main(String...strings) {
FinalVariablesTest finalVariablesTest = new FinalVariablesTest();
System.out.println(" X = "+finalVariablesTest.getX() + " Y = "+finalVariablesTest.getY());
finalVariablesTest = new FinalVariablesTest(4,5);
System.out.println(" X = "+finalVariablesTest.getX() + " Y = "+finalVariablesTest.getY());
}
}