tags:

views:

173

answers:

4

hi,

say i have a class Animal, and then classes Dog and Cat that extend it. Can i have a method then that returns dog or cat, depending on some value? so, something like this, except working :)

public <T extends Animal> getAnimal(){
  if (a)
    return new Dog();
  else
    return new Cat();
}
+3  A: 

well that was a silly question. bed time for me.

A: 

You don't need to use generics in this situation. You could create a factory type method which returns an Animal object:

Animal GetAnimal( AnimalType type )
{
    switch ( type )
    {
        case AnimalType.Dog:
            return new Dog( );
            break;
        case AnimalType.Cat:
            return new Cat( );
            break;
    }       
}

Sorry if the syntax is off a bit, I don't use Java.

Ed Swangren
That's legal Java as well as C#. The uppercase method name is more idiomatic for C# but I think it would compile.
Licky Lindsay
A: 

You dont need to use Generics in that situacion, but you need to add that crazy Generics stuff when dealing with Collections as return types. IE.

 private List<T extends Animal> method1() {
         return new ArrayList<Dog>();
 }

   private List<? super Dog> method() {
            return new ArrayList<Animal>();
        }
Mauricio
A: 
public <T extends Animal> T getAnimal(){
  if (a)
    return (T) new Dog();
  else
    return (T) new Cat();
}
nanda