Designing Classes
This lesson summarizes the nuances to consider when writing new Java classes.
We'll cover the following...
Notes on Class Design
Avoid finalizers as they slow down performance and run non-deterministically or may never run at all. Use
try-with-resources
ortry-with-finally
to ensure code cleanup.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
Always override
hashCode()
when you overrideequals()
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
andy
andx.equal(y)
then ...