Skip to content
Advertisement

Using generics with custom object in method parameters

I have 2 classes as below ::

JavaScript

And I have a method in a service class :

JavaScript

Now I need to pass ItemA or ItemB based upon some conditions in the caller. The return type doesn’t change in either case. How I can do that using generics or wild cards.

This is what I am trying to achieve :

JavaScript

Is the above a good way to handle the scenario or please suggest a better approach. I am new to generics so need your kind help.

Advertisement

Answer

I think that a combination of Polymorphism and Generics could be the way to go.

Consider having an interface Item and change your classes correspondingly

JavaScript

Then your method would become

JavaScript

But beware writing conditions based on the class types, as it’s a common anti pattern

i.e. it’s better avoid code like this

JavaScript
Advertisement