I am implementing an equals method for my class. I want to check if the object passed in is a derived type of the current class so i can return saying they are not equal.
I currently have:
@Override public boolean equals(Object obj){
if(!(obj instanceof Car)){
return false;
}
Car car = (Car)obj;
return car.Number == this.number && car.Age == this.age;
}
So i also have a Taxi extends Car
So if i compare equals I want it to return false in this instance:
Car car = new Car();
Taxi taxi = new Taxi();
print(car.equals(taxi)); // should be false but is currently true
My current fix is to add this to my equals method in Car:
if(!(obj instanceof Car) || (obj instanceof Taxi)){
return false;
}
But this is a pain if every time i add a new derived type from Car i have to add each one manually to this check. Is there some built in way to check if its exactly Car and not a derived type of Car?
>Solution :
You can compare the object’s runtime Class instance directly to Car::class.
if (!obj.getClass().equals(Car::class)){
return false;
}
If the instance is of a subclass of Car, then getClass will return that class rather than Car::class, and the two will not compare equal.