-4

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

Vig Killa
  • 19
  • 6
  • If `o` is an instance of `Book`, it casts `o` to `Book` and gets its ID. What aspect is confusing you? – khelwood Mar 26 '18 at 15:44
  • Look up "casting". You get an `Object` parameter, check if it is of type `Book` (using `instanceof`), and if it is you cast it to `Book` so you can call a `Book` method (`getId()`) on it. – Modus Tollens Mar 26 '18 at 15:46
  • 1
    It's effectively shorthand for `Book b = (Book) o;` `return id == b.getId();` An `Object` doesn't have the method `getId()` but `Book` does. `o instanceof Book` is there to ensure that `o` is of type `Book` or is a subtype of `Book` prior to casting. – d.j.brown Mar 26 '18 at 15:47

3 Answers3

0

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.

0
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.

farmlandbee
  • 345
  • 1
  • 3
  • 14
-1

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.

Bradley H
  • 339
  • 1
  • 7