Overloading methods
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.
Sample code
Cont'd
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.
Example code for overriding
hashCode()
Cont'd
output
Overridding toString()
Reason to override toString()
● It is useful in printing the object in the format
what we need.
Example code to override toString()
Sample output

Overriding methods

  • 1.
  • 2.
    Steps to overrideequals() ● 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.
  • 4.
  • 5.
    Overriding hashCode() ● Bothequal() 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.
    Example code foroverriding hashCode()
  • 7.
  • 8.
  • 9.
    Overridding toString() Reason tooverride toString() ● It is useful in printing the object in the format what we need.
  • 10.
    Example code tooverride toString()
  • 11.