i want to know how does this method works? Especially this part of code "((Book) o).getId()"
public boolean equals(Object o){
if (o instanceof Book){
return id == ((Book) o).getId();
}
return false;
}
Thank you
public boolean equals(Object o){
if (o instanceof Book){
return id == ((Book) o).getId();
}
return false;
}
The method is passed an object, instanceof
checks if the object passed into the method is of type Book
.
If the object is of type Book
then it enables you to safely cast the object to a Book
.
Now the object is a Book
- you are able to use the methods that the Book
class has.
If the Book
object o
has the same value as id
- it will return true
else false
.
If the object is not a book, it will return false
as a default.