【发布时间】:2014-11-25 20:35:26
【问题描述】:
这是我的场景 我有 3 节课。
class Animal {
public getWeight(){ ..... }
public getHeight(){ ..... }
}
class Dog extends Animal {
public getDogType() { ...}
}
class Cat extends Animal {
public getCatType(){....}
}
还有一个不同的方法,它返回一个以 Object 作为参数的 Animal 类型
public Animal translate(CustomObject o){
... so many calculations here
}
这里 translate 方法返回 Animal 对象,但是我需要使用相同的方法来返回 Dog 和 Cat 类型,而不需要进行类型转换。我知道我必须在这里使用泛型,但是如何编辑 translate 方法以支持泛型,以便我可以将 Class 类型传递给它的参数,如果使用 Cat 参数调用它返回 Cat 对象,如果使用 Animal 参数和 Dog 调用它返回 Animal 对象如果使用 Dog 参数调用对象。
例如:- Cat newCat = translate(object, Cat.class); //should return cat object and not animal obj
而不是
Cat newCat = (Cat)translate(object, Cat.class)
谢谢。
【问题讨论】:
标签: java generics polymorphism