Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if the object passed into a method isn't a derived type?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading