Search code examples
javaequalseffective-java

Equals method in Joshua Bloch's Effective Java


Please look at this link of Joshua Bloch's Effective Java.

In second paragraph, the author says:

The class is private or package-private, and you are certain that its equals method will never be invoked. Arguably, the equals method should be overridden under these circumstances, in case it is accidentally invoked:

@Override public boolean equals(Object o) {
     throw new AssertionError(); // Method is never called
}

Please explain this. I am getting confused by the author's use of term private class and that why is there a need to override equals method when we know for certain that it won't be invoked.


Solution

  • A class can be private only if it is an inner class.

    As for the "why" is there a need to override equals, the reason is that by writing it as you have shown you will ensure that the method is never called intentionally. The moment six months in the future, when a new developer on the project will call equals on that class, the method will throw and signal that it is not correct to call it. That's a good thing; it prevents "forgetting" about it.