What is the difference between identity and equality in OOP?

What is the difference between identity and equality in OOP (Object Oriented Programming)?


Solution 1:

  • identity: a variable holds the same instance as another variable.

  • equality: two distinct objects can be used interchangeably. they often have the same id.

Identity

For example:

Integer a = new Integer(1);
Integer b = a;

a is identical to b.

In Java, identity is tested with ==. For example, if( a == b ).

Equality

Integer c =  new Integer(1);
Integer d = new Integer(1);

c is equal but not identical to d.

Of course, two identical variables are always equal.

In Java, equality is defined by the equals method. Keep in mind, if you implement equals you must also implement hashCode.

Solution 2:

Identity determines whether two objects share the same memory address. Equality determines if two object contain the same state.

If two object are identical then they are also equal but just because two objects are equal dies not mean that they share the same memory address.

There is a special case for Strings but that is off topic and you'll need to ask someone else about how that works exactly ;-)

Solution 3:

Identity means it is the same object instance while equality means the objects you compare are to different instances of an object but happen to contain the same data.

Illustration (in java)

Date a = new Date(123);
Date b = new Date(123);
System.out.println(a==b); //false
System.out.println(a.equals(b)); //true

So a and b are different instances (different allocations in memory) but on the "data" level they are equal.