Designing Classes

This lesson summarizes the nuances to consider when writing new Java classes.

We'll cover the following...

Notes on Class Design

  1. Avoid finalizers as they slow down performance and run non-deterministically or may never run at all. Use try-with-resources or try-with-finally to ensure code cleanup.

  2. Overriding equals() method should honour the following properties:

    • Reflexivity: x.equals(x) == true

    • Symmetric: x.equals(y) == y.equals(x)

    • Transitivity: x.equals(y) == y.equals(z) == z.equals(x)

    • Consistent: x.equals(y) == x.equals(y) == x.equals(y) == ...

    • Non-nullity: x.equals(null) should equal false

  3. Always override hashCode() when you override equals()

  4. Overriding hashCode() should honor the following properties:

    • Invoking hashCode() on the same object should always return the same integer.

    • If there are two objects x and y and x.equal(y) then ...