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.
The equals() method compares two strings, and returns true if the strings are equal, and false if not.
In java equals() method is used to compare equality of two Objects. The equality can be compared in two ways: Shallow comparison: The default implementation of equals method is defined in Java. lang.
The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.
equals() is a method defined in the Object class thus the default implementation of the . equals() method compares the object references or the memory location where the objects are stored in the heap. Thus by default the . equals() method checks the object by using the “==” operator.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With