【关键字instanceof】
再写一个Cat类
在Test类中创建一个Cat对象c,将c与p1用equals方法进行比较:
Cat c=new Cat();
System.out.println(p1.equals(c));//此句报错,不同类型不可比较
//如果不想报错,需要不同类型比较返回结果为false,则需使用instanceof关键字
使用instanceof关键字:
//对Object提供的equals方法进行重写
public boolean equals(Object obj){
/*
a instanceof b:
判断a对象是否是b这个类的实例,如果是,返回true,如果不是返回false
*/
if(obj instanceof Phone) {
//将obj转为Phone类型:
Phone other=(Phone)obj;
if(this.getBrand()==other.getBrand()&&this.getPrice()==other.getPrice()&&this.getYear()==other.getYear()) {
return true;
}
}
return false;
}