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
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
First, the if statement verify if the variable o is an instance of Book class.
if (o instanceof Book)
Second, if o is a Book then we can cast it into a Book. The code below return an Book object:
Book myVar = (Book) o;
And third, we can call Book methods in myVar. For example:
myVar.getId()
The code you posted do all this in one line. Cast, call a Book method and return a response.
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.
The instanceof
syntax checks if the first object implements or extends the second object. If it does, it returns true. Then, since it is a book, it gets the ID of the object, which is a book.