Equality Method in Joshua Bloch Effective Java

Please look at the Joshua Bloch Effective Java link .

In the second paragraph, the author says:

The class is private or package-private, and you are sure that its equals method will never be called. Perhaps the equals method should be overridden in these circumstances if it is accidentally called:

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

Please explain this. I am confused by the fact that the author uses the term private class, and why there is a need to override the equals method if we know for sure that it will not be called.

+7
java equals effective-java
source share
1 answer

A class can be closed only if it is an inner class.

As for the why, you need to redefine equals , the reason is that by writing it, as you showed, you will see that the method is never called intentionally. At a time when six months in the future, when a new developer in a project will be called equal in this class, this method will call and signal that it is wrong to call it. This is a good thing; this prevents "forgetting" about it.

+8
source share

All Articles