Nil. Hatamova wrote:Why the output is difference for equals() method?
Because any class can override the
equals(Object) method of the
Object class. And the
String class overrides this method and will return
true if and only if the argument is not
null and is a
String object that represents the same sequence of characters as the current (this) object. Your
Book class doesn't override this method, so the
equals(Object) method from the
Object class is inherited. And this method returns
true if and only if the argument refers to the same object as the current (this) object. So the code looks like
A very similar question is asked in
this topic. And many classes from the
Java API override the
equals(Object) method of the
Object class to provide a more meaningful implementation than reference equality. For example all wrapper classes, ArrayList (see
this topic for detailed information),...
Now let's see if you have understood all the above. It's time for a pop quiz question. Consider this code snippet
When I execute this class using the
Book class from your first post, it prints 6x
false. Now it's up to you to make appropriate changes to the
Book class so that when you execute the
TestBook class, this output is produced:
false
true
true
false
false
true
Hope it helps!
Kind regards,
Roel