Sunday, 13 August 2017

java - What is the difference between identity and equality in OOP?



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


Answer




  • identity: a variable holds the

    same instance as another variable.


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






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






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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...