tuskiomi tuskiomi - 1 month ago 8x
Java Question

Can java variables be an unbounded wildcard?

for example, can a variable be something like so:

public <? extends Foo> FooExtension = new FooAugmentation();

without throwing errors, or is there not an implementation of this?

An example of how this would be useful is like so:

public class Human{
private String localName;
private <? extends Animal> FavoriteAnimalInstance;
public Human(String name, <? extends Animal> fav){
FavoriteAnimalInstance = fav;
public <? extends Animal> getFavoriteAnimal(){
return FavoriteAnimalInstance();

with the main Code:

Public class main{
public static void main(String[] a){
Human AnimatedCharacter = new Human('Fry',new Seymour());
"Not the episode with the dog" :
"It's the episode with the dog..");

Or am I over complicating something that could be done more easily than that?


Since the discussion starts to get out of hand...

Your code, if it was valid, would result in a Human object that had a favorite animal. But the Human would have no way of telling the compiler, what specific type of animal it was, since all it knew would be "something that extends Animal (or Animal itself)".

Effectively, it would be the same as...

private Animal animal;

Obviously, you don't want want to hard-code your animal there...

private Seymore favoriteAnimalInstance;

So, the only real "choice" you have, is making the instance of Human know what the favorite animal is...

public class Human<A extends Animal> {

   private A favoriteAnimal;

   public A getFavoriteAnimal(){
      return favoriteAnimal;

public static void main(String[] args) {

   Human<Seymour> fry = new Human<Seymour>();
   // etc.
   boolean petrified = fry.getFavoriteAnimal().isPetrifiedInDiamondium();

Besides that? Not many choices, since the compiler needs to know the type of the object before you can call methods on it. If the compiler only knows "Animal", then you only have animal methods, even if the actual object during runtime is extremly more complex and has dozens of other methods.

And yes, you could reflection to analyze the object at runtime and call methods, etc. - but trust me, that's not a good idea and it doesn't solve this problem.

Oh, and please start your variable names with lower case, thanks. Also "Instance" is pretty superfluous here, since everything that is not a class, is obviously an instance, so it doesn't actually add anything meaningfull here.