手撸代码实现equals方法

时间:2022-01-23 17:07:26
重点都在注释里面写了,这里就不再重复叙述,贴上代码到博客主要是备用。

package equals;

class Book extends Object {    private String title;    private double price;

    public Book(String title, double price) {        this.title = title;        this.price = price;    }

    public String toString() {        return "" + this.title + "" + this.price;    }

    public boolean equals(Object obj) {        if (obj == this) {            return true;//传入的对象跟当前对象的地址值一样,说明是同一对象,为真。        }        if (obj == null) {            return false;//传入对象为空        }        if (!(obj instanceof Book)) {            return false;//判断传入的obj对象是否是Book类的实例化对象,如果不是,返回false。        }        Book book = (Book) obj;//向下将obj对象转型为Book类对象。这里是强制转型所以加上(Book)        if (this.title.equals(book.title) && this.price == book.price) {            return true;        }        return false;    }}

public class demo {    public static void main(String[] args) {        Book bookA = new Book("java",78.1);        Book bookB = new Book("java",78.1);        System.out.println(bookA.equals(bookA));    }}