Below is written in javadocs
The equals method for class Object implements the most discriminating
possible equivalence relation on objects; that is, for any non-null
reference values x and y, this method returns true if and only if x
and y refer to the same object (x == y has the value true).
Does it mean object1.equals(object2) return true only when object1==object2.
Below example at In Java, what is a shallow copy?
class Foo { private Bar myBar; ...
public Foo shallowCopy() {
Foo newFoo = new Foo(); newFoo.myBar = myBar; return newFoo; }
public Foo deepCopy() { Foo newFoo = new Foo(); newFoo.myBar = myBar.clone(); //or new Bar(myBar) or myBar.deepCopy or ... return newFoo; } } Foo myFoo = new Foo();
Foo sFoo = myFoo.shallowCopy();
Foo dFoo = myFoo.deepCopy();
myFoo.myBar == sFoo.myBar => true
myFoo.myBar.equals(sFoo.myBar) => true
myFoo.myBar == dFoo.myBar => false
myFoo.myBar.equals(dFoo.myBar) => true
If First understading is correct how come myFoo.myBar.equals(dFoo.myBar) => true
The default implementation for equals is the same as
==However it is common practice to override this method and give it an implementation where two objects are equal if the type and contents are the same. It should always be true when
==is true.