私有静态最终变更的价值[关闭](value of private static final changes [closed])

在过去的几个小时里,我一直对以下情况感到困惑。 我有一个Fraction类,零分数的常量,如下所示:

class Fraction{ private static final Fraction ZERO = new Fraction(0,1); public static Fraction zero(){ return ZERO; } [etc] }

随后,我发现ZERO的值在执行过程中发生了变化,其中:

System.out.println(Fraction.zero()); Fraction half = new Fraction(1, 2); System.out.println(Fraction.zero());

输出:

1/1 1/2

显然,产生的价值应该是0/1,更重要的是,固定的。 问题绝对不在于Fraction类和与之相关的GCD计算器的实现,因为我过去已成功并广泛地使用它们。

关于这种奇怪行为的原因的任何想法和想法都非常感激。

I have been baffled by the below for the past few hours. I have a Fraction class with a constant for the zero fraction, like so:

class Fraction{ private static final Fraction ZERO = new Fraction(0,1); public static Fraction zero(){ return ZERO; } [etc] }

Subsequently, I discovered that the value of ZERO changes in the course of execution, in that:

System.out.println(Fraction.zero()); Fraction half = new Fraction(1, 2); System.out.println(Fraction.zero());

outputs:

1/1 1/2

while obviously the value produced should be 0/1, and, more importantly, fixed. The problem is definitely not with the implementation of the Fraction class and the GCD calculator associated to it, since I have used them successfully and extensively in the past.

Any ideas and thoughts on the cause of this strange behaviour are much appreciated.

最满意答案

你应该向我们展示类中其余的代码 - 我的猜测是分子和分母变量已被标记为static而它们确实应该是常规实例变量。

无论问题是什么, final字段更改引用的对象的内容都没有错 - final修饰符只能确保不能使字段引用另一个对象。 对象本身是不受保护的。

You should show us the rest of the code in the class - my guess would be that the numerator and denominator variables have been marked as static while they really should have been regular instance variables.

Whatever the problem is, there is nothing wrong with the contents of an object referred to by a final field changing - the final modifier only ensures that the field cannot be made to refer to another object. The object itself is unprotected.

更多推荐