So I'm fairly new to programming in the real world (outside of academic projects) and have come across lots of posts saying that using instanceof
is a bad thing to use to determine what class a specific object is.
My situation is that I have three classes, a base product class, one that extends off that and another that extends off that. These are all stored in the same table in a database and I have some code that needs to use the methods on each to pull data off them.
What is the best practice to get around this way of doing it? I have read some things about polymorphism but I can't find any examples that fix the issue I have. They all usually override a method which for me won't work as I need to pull different things from the different objects.
Is there a better way to do this or am I stuck with using instanceof
or some sort of reflection to get the fields specific to the objects?
instanceof
is wrong; trying to find the class of an object is usually the problem. Not always wrong, but probably in your case it is. Maybe if you tell us what you're trying to accomplish, we can suggest a solution using polymorphism.getSpecifics()
that is implemented differently on each, with each returning the data specific to the class?