You have to look how this is called:
someObject.equals(someOtherObj);
This invokes the equals
method on the instance of someObject
. Now, inside that method:
public boolean equals(Object obj) { if (obj == this) { //is someObject equal to obj, which in this case is someOtherObj? return true;//If so, these are the same objects, and return true }
You can see that this
is referring to the instance of the object that equals is called on. Note that equals()
is non-static, and so must be called only on objects that have been instantiated.
Note that ==
is only checking to see if there is referential equality; that is, the reference of this
and obj
are pointing to the same place in memory. Such references are naturally equal:
Object a = new Object(); Object b = a; //sets the reference to b to point to the same place as a Object c = a; //same with c b.equals(c);//true, because everything is pointing to the same place
Further note that equals()
is generally used to also determine value equality. Thus, even if the object references are pointing to different places, it will check the internals to determine if those objects are the same:
FancyNumber a = new FancyNumber(2);//Internally, I set a field to 2 FancyNumber b = new FancyNumber(2);//Internally, I set a field to 2 a.equals(b);//true, because we define two FancyNumber objects to be equal if their internal field is set to the same thing.