- The first case creates two different
Objects
, each one with its own reference/entity in memory. Instances from the same Class, but different Objects anyway.
- In the second case, you assign the same
Object
reference to the new Dog
instance: they both refer to the same Object
.
The ==
operator compares the references of objects. In your second case, they both reference the same Dog
.
This is for Objects
, not primitives; Regarding primitives, the value itself is compared.
Java Specification Equality Operators:
If the operands of an equality operator are both of either reference
type or the null type, then the operation is object equality. A
compile-time error occurs if it is impossible to convert the type of
either operand to the type of the other by a casting conversion
(§5.5). The run-time values of the two operands would necessarily be
unequal.
At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result
is false.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…