class Book{
private String title;
private double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
//setter,getter略
//本类接受自己的引用便于调用类中属性私有化操作
//本类接受本类引用与当前对象比较
public boolean compare(Book book) {
//先对比较对象进行非空判断防止空指向异常
if (book == null) {
return false;
}
//再与当前对象比较内存地址,如相等就不用后续比较了
if (this == book) {
return true;
}
//再进行各自属性的比较
if ((this.title).equals(book.title)
&& (this.price == book.price)) {
return true;
} else {
return false;
}
}
}
public class TestDemo {
public static void main(String[] args)
{
Book ba = new Book("语文",10);
Book bb = new Book("语文",10);
if (ba.compare(bb)) {
System.out.println("同一对象");
} else {
System.out.println("不同对象");
}
}
}
对象之间比较
最新推荐文章于 2025-04-10 17:16:26 发布