先创建一个Cat类,我没有复制包,所以在复制粘贴的时候可以在任意一个包下
public class Cat {
public static void main(String[] args) {
System.out.println("hnskahfkl");
}
}
在创建一个Phone类
public class Phone {
//属性
private String brand;
private double price;
private int birthday;
public String name;
//set和get方法
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 getBirthday() {
return birthday;
}
public void setBirthday(int birthday) {
this.birthday = birthday;
}
//构造器
public Phone() {
}
public Phone(String brand, double price, int birthday) {
this.brand = brand;
this.price = price;
this.birthday = birthday;
}
//方法de重写
@Override
public String toString() {
return "Phone{" +
"brand='" + brand + ''' +
", price=" + price +
", birthday=" + birthday +
'}';
}
public boolean equals(Object obj) {
//this指的是当前调用方法的对象 ------//return (this == obj);
//将obj转化为Phone类型
//instanceof运算符
//a instanceof b 判断对象a是否是b类的实例,是,返回true,不是,返回flase
if (obj instanceof Phone){
Phone a=(Phone) obj; //强制类型转换 int a=10; (Double)a Phone other=(Phone) obj;
if (this.getBrand()==a.getBrand()&&this.getPrice()==a.getPrice()&&this.getBirthday()==a.getBirthday()){
return true;
}
return false;
}
return false;
}
// @Override //--------这段代码是按快捷键生成的,是正确的
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Phone phone = (Phone) o;
// return Double.compare(phone.price, price) == 0 && birthday == phone.birthday && Objects.equals(brand, phone.brand);
// }
}
在创建一个Test类
//一般在子类,对equals方法进行重写
public class Test{
public static void main(String[] args) {
//p1在栈里存的地址
Phone p1=new Phone("apple1",1000,2010);
Phone p2=new Phone("apple1",1000,2010);
System.out.println(p2);
//==比较的是两侧的值是否相等。
//==对于引用数据类型来说,比较的是二个数据的地址值,一定不相等
System.out.println(p2==p1);//p1,p2的地址一定不相等
//boolean s = p1.equals(p2);
System.out.println("p1.equals(p2):"+p1.equals(p2));//equals比较对象具体内容是否相等
Cat c1=new Cat();
System.out.println("p1.equals(c1):"+p1.equals(c1));
System.out.println();
}
// public boolean equals(Object obj) {
// Phone other=(Phone)obj;
// if (this){//-----为什么此处会报错,在Test类继承phone类后就不会出错
// return true;
// }
// return false;
// }
}
运行结果:



