Check my comments in the your code:-
public boolean equals(Object o) {
//below line is comparing if o refers to the same current object
if (o == this) { return true; }
//below line is checking if o is null, in that case it will return false
if (o == null) { return false;}
//checking if the class of o is Book, if not return false
if (!o.getClass().equals(Book.class)) {return false; }
//Casting the o from Object to Book class
Book aBook = (Book) o;
//comparing the book object's year. title and author, if all three are equal then only two Book objects are equal
return aBook.year == year && aBook.title.equals(title) && aBook.author.equals(author);
}
You will call the above method like below:-
Book object1=new Book();
Book object2=new Book();
object1.equals(object2);
Scenario 1:-First line in your code checks, whether object1 and object2 are reference to the same object:-
Book object1=new Book();
Book object2=object1;
object1.equals(object2);
Above situation is handled in your first line, you can see in scenario 1, object2 is basically the same current object that is object1.
Your null and class conditions can be written like:-
if((o == null) || (o.getClass() != this.getClass())) return false; //preferred
Don't get tempted to use:-
if(!(o instanceof Book)) return false; //avoid
because above condition fails to return false if the argument is a subclass of the class Book.
In the last part of your equals method, you are just comparing the three attributes of two Book objects and calling the two objects equal only if all the three attributes are equal.