• Post Reply Bookmark Topic Watch Topic
  • New Topic

Should I use Generics or Polymorphism in this case?  RSS feed

 
Jacky Luk
Ranch Hand
Posts: 634
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to pass some parameters to a printReport function,
in which there is a parameter known as a List<>
of some report data.
This can be
List<Sales>
List<Customers>
etc
Should I construct 10 polymorphic functions to deal with each type
Or there are some ways like using generics to cover each one of them
Like
List<Object>
Could you please raise an example where appropriate?
Thanks
Jack
 
Campbell Ritchie
Marshal
Posts: 56592
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe, you should have a Report interface which those classes implement and use a List<Report>. That is both generics and polymorphism!
 
Jacky Luk
Ranch Hand
Posts: 634
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Maybe, you should have a Report interface which those classes implement and use a List<Report>. That is both generics and polymorphism!




I've thought about it for a while. And wonder what should be put inside the ellipsis?
a List<Object>, or should I declare more than one interface method?
Thanks
Jack

 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I understand your requires, then maybe make the interface generic as well, take a type T and use it in the printReport's argument. Implementers would specify what type they care to use.

 
Wendy L Gibbons
Bartender
Posts: 1111
Eclipse IDE Oracle VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i would make an interface of Printable or some such name and that has one method called PrintReport

then each class (customer, sales etc ) would implement Printable and have it's own PrintReport method

the you could have a list<Printable> and loop around the list calling PrintReport and it wouldn't matter what you placed in the list.

so as someone else said generics and polymorphism pretty well go together.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!