Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Overriding methods

480 views

Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Overriding methods

  1. 1. Overloading methods
  2. 2. Steps to override equals() ● Do this check -- if yes then return true. ● Do null check -- if yes then return false. ● Do the instanceof check, if instanceof return false than return false from equals in Java ,we can use getClass() method for type identification because instanceof check returns true for subclass also. if((obj == null) || (obj.getClass() != this.getClass())) return false; ● Type cast the object; note the sequence instanceof check must be prior to casting object. ● Compare individual attribute starting with numeric attribute because comparing numeric attribute is fast and use short circuit operator for combining checks.
  3. 3. Sample code
  4. 4. Cont'd
  5. 5. Overriding hashCode() ● Both equal() and hashCode() belong to Object class. ● It is not always necessary to override hashcode and equals. ● But if you think you need to override one, then you need to override both of them. ● We must overload hashCode() when equals() is overrided because to access the collection class effectively without violating the rules.
  6. 6. Example code for overriding hashCode()
  7. 7. Cont'd
  8. 8. output
  9. 9. Overridding toString() Reason to override toString() ● It is useful in printing the object in the format what we need.
  10. 10. Example code to override toString()
  11. 11. Sample output

×