Designing Classes
Explore how to design Java classes effectively by understanding best practices in overriding equals and hashCode methods, managing immutability, cloning, encapsulation, and using nested classes. This lesson helps you write safer, cleaner, and more maintainable classes in Java.
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-resourcesortry-with-finallyto ensure code cleanup.Overriding
equals()method should honour the following properties:Reflexivity:
x.equals(x) == trueSymmetric:
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
xandyandx.equal(y)thenx.hashCode() == y.hashCode().On the contray if
x...