1
votes

Here is my scenario I've 3 classes.

class Animal {
   public getWeight(){ ..... }
   public getHeight(){ ..... }
}

class Dog extends Animal {
   public getDogType() { ...}
}

class Cat extends Animal {
   public getCatType(){....}
}

And there is a different method which returns an Animal type taking an Object as a parameter

public Animal translate(CustomObject o){
     ... so many calculations here
}

Here translate method returns Animal Object, but I need to use the same method to return Dog and Cat types too without typecasting. I know I have to use Generics here but how can I edit translate method to support Generics, so that I can pass the Class type to its parameter and it returns Cat object if called using Cat parameter and Animal object if called using Animal parameter and Dog object if called using Dog parameter.

eg:- Cat newCat = translate(object, Cat.class); //should return cat object and not animal obj instead of

Cat newCat = (Cat)translate(object, Cat.class)

Thanks.

2

2 Answers

1
votes

Try public <T extends Animal> translate(CustomObject o, Class<T> clazz).

3
votes

You need a self referencing bound:

class Animal<T extends Animal<T>> {
   public getWeight(){ ..... }
   public getHeight(){ ..... }
   public T translate(CustomObject o){
     //... so many calculations here
   }
}

class Dog extends Animal<Dog> {
   //
}

class Cat extends Animal<Cat> {
   //
}

You may consider making translate() abstract, allowing subclasses to handle their own implementations.