Java Programming – Alternatives to ‘instanceof’ in Java

javapolymorphismprogramming practices

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?

Best Answer

The reason instanceof is discouraged is that it's not OOP.

There should be no reason for the caller/user of an object to know which concrete class it is an instance of beyond which type the variable it is declared as.

If you need different behavior in subclasses add a method and implement them differently.