Object类提供了一个equals方法,作用:比较对象具有的内容是否相等
Phone:
package com.pyk;
public class Phone {
private String brand;//品牌型号
private double price;//价格
private int year;//出产年份
//方法
public String getBrand() {
return brand;
}
public void setBrand(String Brand) {
this.brand=brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price=price;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year=year;
}
//空构造器
public Phone() {
}
//三个参数的构造器
public Phone(String brand,double price,int year) {
this.brand=brand;
this.price=price;
this.year=year;
}
public String toString() {
return "手机品牌:"+brand+"价格:"+price+"出产年份:"+year;
}
//对Object提供的equals方法进行重写
public boolean equals(Object obj){
//将obj转为Phone类型:
Phone other=(Phone)obj;//向下转型,为了获取子类中特有的内容
if(this.getBrand()==other.getBrand()&&this.getPrice()==other.getPrice()&&this.getYear()==other.getYear()) {
return true;
}return false;
}
}
Test:
package com.pyk;
public class Test {
public static void main(String[] args) {
Phone p1=new Phone("华为P40",2000.5,2020);
Phone p2=new Phone("华为P40",2000.5,2020);
//比较p1和p2
System.out.println(p1==p2);//此处比较的是两个对象的地址值
//Object类提供了一个equals方法,作用:比较对象具有的内容是否相等
boolean flag=p1.equals(p2);
System.out.println(flag);//由于equals是由父类Object提供的
//父类里面提供的equals方法为:
/*
public boolean equals(Object obj){
return (this==obj);
}
obj表示传入的p2,this表示p1,因此底层依然是比较p1和p2的地址
因此我们需要对object提供的equals方法进行重写
*/
}
}