Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
user961690 Avatar asked Mar 23 '15 10:03

user961690


People also ask

What is equals () method in Java?

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

What is the importance of equals method in Java?

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.

What is equals () and hash code () method?

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.

How is equals implemented in Java?

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.


1 Answers

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.

like image 154
Andrea Bergia Avatar answered Nov 25 '22 08:11

Andrea Bergia