• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generic wildcards  RSS feed

 
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have the following classes:



In the main method, I want to create a list that accepts any instance of a class that extends Animal BUT I don't want to accept an Animal itself. I know I can mark the Animal class as abstract but what if the class implementer is not me and it's not abstract? How can I achieve this?

Thanks in advance,
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think you're going to be able to do this at compile time. One thing you could do is create your own List class (e.g. extend ArrayList), and override the add methods to throw an exception if an Animal is added (or some other mechanism where you only allow objects to be added via code that can check the type).
 
Marshal
Posts: 56605
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Start with the Java™ Tutorials. I am not sure you can prevent a Foo<T extends Animal> from including an Animal object. You might be able to test with getClass() and T.class in the add() method and throw an Exception if the two are the same.

Sorry I can't think of anything else. Anybody else?
 
Ranch Hand
Posts: 781
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One possibility - create an abstract class that extends Animal (say YourAnimal) , make all your classes extend YourAnimal and then have a Foo <T extends YourAnimal> .
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!