2

Under what circumstances should I begin to consider overriding any of the following methods?

  • clone()
  • equals()
  • finalize()
  • hashCode()
  • toString()

Some of these have some obvious, somewhat specific answers, but I'm wondering more so about general conditions under which it would considered good practice to implement them.

Trevor Sears
  • 459
  • 8
  • 24
  • I think because most of java objects implements java.lang.Object class, you could want to extend this sub classes. But in case you have a new java type with different implementation you could implement it. – Fady Saad May 31 '17 at 02:00
  • @user7790438 Every object created in Java inherit from the Object class, it's impossible to avoid it. However Java's default implementations of these methods are basically useless. Almost every class you make will have a "different implementation." – Headline May 31 '17 at 02:03

2 Answers2

6

clone()

Implement if you want an easy way to copy the object.

Many people discourage use of clone() and suggest using a copy-constructor instead. E.g. see Clone() vs Copy constructor- which is recommended in java.


equals()

Implement if you need to compare two instances for equality.

Required if object will be used as key in a HashMap (or similar), or inserted into a HashSet (or similar). Highly recommended of used in the TreeXxx variants, for compatibility with compareTo(), i.e. if class implements Comparable.


hashCode()

Implement if object will be used as key in a HashMap (or similar), or inserted into a HashSet (or similar).

Generally a good idea to always implement if you implement equals().


toString()

Generally implement to make debugging easier, especially if object will be inserted into a collection.

Implement if object has a simple textual representation, and you want to be able to output it without calling a method (e.g. getName() or getDescription()).


finalize()

Never. No code should rely on finalize() for resource clean-up, since there is no guarantee when, or even if, it will be called.

Resource-owning classes should implement AutoCloseable instead.

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

Generally I follow the following principle: Always override at least equals() and toString() (maybe even clone(), too) if the software you're creating will be used by others (like an API or something).

If it's just for personal small things I would at least make a toString() since they can be very handy, but it's all up to you: the programmer.

Headline
  • 1,518
  • 1
  • 9
  • 13