I'm building something that requires some polymorphism utilisation and I was wondering what the flaws in this method of avoiding type comparison might be.
Essentially, I want to place an enum in the base class and then change the value of that enum depending on what the current class is and then use the enum to do type comparison instead.
So for the constructors:
public class Animal{
private AnimalType animalType; // the enum
public Animal(AnimalType animalType)
{
this.animalType = animalType;
}
public getAnimalType()
{
return animalType;
}
}
public class Cat{
public Cat()
{
super(AnimalType.CAT);
}
}
public class Dog{
public Dog()
{
super(AnimalType.DOG);
}
}
And then instead of:
if (dog instanceof Dog)
We do:
if (dog.getAnimalType() == AnimalType.DOG)
Then would this make any difference to computational speed? What are the flaws that you can think of when doing this? Is there anything vital here that I have personally missed when I came up with this?
I know this isn't perfect for various reasons, but if there are going to be thousands of these comparisons performed per second then shaving off a few microseconds is worth it.