Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between identity and equality in OOP?

Tags:

java

object

oop

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

like image 310
sevugarajan Avatar asked Nov 07 '09 12:11

sevugarajan


People also ask

What is the difference between equality of object and equality of reference?

Equality of objects means when two separate objects happen to have the same values/state. Whereas equality of references means when two object references point to the same object. The == operator can be used to check if two object references point to the same object.

What is identity in object oriented concepts?

In object-oriented programming, object-oriented design and object-oriented analysis, the identity of an object is its being distinct from any other object, regardless of the values of the objects' properties. Having identity is a fundamental property of objects.

What is the difference between the Equals method and equality operator?

The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.

When would you use == vs equal () and what is the difference?

== is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality.


2 Answers

  • 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.

like image 171
Andreas Petersson Avatar answered Sep 23 '22 01:09

Andreas Petersson


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 ;-)

like image 33
Antz Avatar answered Sep 25 '22 01:09

Antz