class Book{
private String title;
private int price;
public Book(String title,int price){ //构造器
this.title=title;
this.price=price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public boolean equals(Object obj){
if(this==obj){ //比较地址是否相同
return true;
}
if(obj==null){ //判断要比较的对象是否为空
return false;
}
if(!(obj instanceof Book)){// 判断数据类型是否一样
return false;
}
Book book=(Book) obj; //强转数据类型
if(this.title.equals(book.title)&&
this.price==book.price){ //自定义比较规则
return true;
}else {
return false;
}
}
@Override
public String toString() {
return "Book [title=" + title + ", price=" + price + "]";
}
}
public class EqualsTest {
public static void main(String[] args) {
Book book1=new Book("java",20);
Book book2=new Book("java",21);
System.out.println(book1.equals(book2));
book1.toString();
book2.toString();
}
}
Demon丶ZY
相关分类