21
Methods Common to All Objects MANISH ADLAKHA

Methods common to all objects

Embed Size (px)

Citation preview

Page 1: Methods common to all objects

Methods Common to All Objects

MANISH ADLAKHA

Page 2: Methods common to all objects

All methods of Object class have explicit general contracts because they are meant to be overridden.

When a class overrides these methods, the contracts must be obeyed otherwise the classes dependent on these contracts will not function properly.

Methods of object class• equals()• hashCode() • toString()• clone()• finalize()

Object class methods

Page 3: Methods common to all objects

ITEM 8Obey the general contract when

overriding equals

Page 4: Methods common to all objects

When a class has a notion of logical equality which extends mere object identity

And the behavior is not by a superclass Need to find whether they are logically

equivalent and not whether they refer to same object

Allows instances to serve as map keys and show set behavior

When to implement equals()

Page 5: Methods common to all objects

Equivalence relation Reflexive – x.equals(x) -> true Symmetric –

x.equals(y) -> true => y.equals(x) -> true Transitive Consistent -> should return same values

consistently when equals is called For a not-null reference, x.equals(null) ->

false

General contract

Page 6: Methods common to all objects

Use the == operator to check if the argument is a reference to this object

Use the instanceof operator to check if the argument has the correct type

Cast the argument to the correct type For each significant field in the class, check if that field

of the argument matches the corresponding field of this object

When you are finished writing, ask yourself three questions:

• Is it symmetric?• Is it transitive?• Is it consistent?

How to implement a good quality equals() method

Page 7: Methods common to all objects

Item 9Always override hashCode when you

override equals

Page 8: Methods common to all objects

You must override hashCode in every class that overrides equals.

Failure to do so results in violation of the general contract for Object.hashCode, which prevents the class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

Page 9: Methods common to all objects

When invoked on an object more than once, hashCode() must consistently return the same integer, provided no information used in equals comparisons on the object is modified

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

Not necessary that hashCode() called on two unequal objects return distinct hashcode numbers but doing so improves the performance of hashtables.

General contract

Page 10: Methods common to all objects

The key provision that is violated when you fail to override hashCode is the second one: equal objects must have equal hash codes.

We may exclude redundant fields from the hashCode computation.

Do not be tempted to exclude significant parts of an object from the hash code computation to improve performance.

Key points

Page 11: Methods common to all objects

Item 10Always override toString()

Page 12: Methods common to all objects

Default return - class name followed by an “at” sign (@) and the unsigned hexadecimal representation of the hash code, for example, “PhoneNumber@163b91

General contract• returned string should be “a concise but informative

representation that is easy for a person to read”

toString()

Page 13: Methods common to all objects

providing a good toString() implementation makes your class much more pleasant to use.

toString() invoked when an object is◦ Passed to println() and printf()◦ Used in string concatenation operator or assert◦ Printed by the debugger

When practical, the toString method should return all of the interesting information contained in the object

Whether or not you decide to specify the format, you should clearly document your intentions

provide programmatic access to all of the information contained in the value returned by toString()

Page 14: Methods common to all objects

Item 11Override clone() judiciously

Page 15: Methods common to all objects

A flag interface that advertises that an object permits cloning

Lacks a clone() method Object class’ clone() is protected -> so cannot be used

without using reflection Cloneable interface determines the behavior of Object’s

clone() implementation It modifies the behavior of a protected method on a

superclass

Cloneable Interface

Page 16: Methods common to all objects

x.clone() !=x x.clone().getclass() == x.getclass() x.clone().equals(x) should be true but it is not an

absolute requirement No constructors are to be called when creating a

clone

General contract

Page 17: Methods common to all objects

If you override the clone method in a nonfinal class, you should return an object obtained by invoking super.clone().

In practice, a class that implements Cloneable is expected to provide a properly functioning public clone method.

In effect, the clone method should function as another constructor; you must ensure that it does no harm to the original object and that it properly establishes invariants on the clone

The clone architecture is incompatible with normal use of final fields referring to mutable objects

Key points

Page 18: Methods common to all objects

Item 12Consider implementing Comparable

Page 19: Methods common to all objects

Method of the comparable interface Not declared in Object class Allows order comparison along with equality comparisons Indicates a natural ordering of instances of a class

compareTo()

Page 20: Methods common to all objects

sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y

(x.compareTo(y) > 0 && y.compareTo(z) > 0) implies x.compareTo(z) > 0

x.compareTo(y) == 0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z

(x.compareTo(y) == 0) == (x.equals(y)) – Strongly recommended but not strictly required

General contract

Page 21: Methods common to all objects

Violating the compareTo() contract breaks the classes dependent on comparison◦ Sorted collections – TreeSet and TreeMap◦ Utility classes collections and Arrays