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.