Inheritance, Generics and Casting in Java
I have two classes which both extends Example
.
public class ClassA extends Example {
public ClassA() {
super("a", "class");
}
...
}
public class ClassB extends Example {
publ开发者_开发知识库ic ClassB() {
super("b", "class");
}
...
}
public class Example () {
public String get(String x, String y) {
return "Hello";
}
}
So thats all very well. So suppose we have another class called ExampleManager. With example manager I want to use a generic type and consequently return that generic type. e.g.
public class ExampleManager<T extends Example> {
public T getExample() {
return new T("example","example"); // So what exactly goes here?
}
}
So where I am returning my generic type how do i get this to actually work correctly and cast Example
as either classA
or classB
?
Many Thanks
You can't use a generic type to instantiate new object (i.e. you can't do new T(params)
).
When you are creating a concrete instance of object (that is, you use new), you have know the actual implementing class, you can't use a generic type.
What are you actually trying to achieve? How do you decide whether you want to create ClassA or ClassB?
Try this:
public class ExampleManager {
public ClassA createClassA() {
return new ClassA("example","example");
}
public ClassB createClassB() {
return new ClassB("example","example");
}
}
or this:
public class ExampleManager {
public Example createExample() {
if(a == b) {
return new ClassB("example","example");
}
return new ClassB("example","example");
}
}
As others have said, you can't use new to create a new instance of an unknown type. Without using reflection, you could make ExampleManager an abstract superclass of factories.
public abstract class ExampleManager<T extends Example> {
public abstract T getExample(String x, String y);
}
public class ClassAManager extends ExampleManager<ClassA> {
public ClassA getExample(String x, String y) {
return new ClassA(x, y);
}
}
public class ClassBManager extends ExampleManager<ClassB> {
public ClassB getExample(String x, String y) {
return new ClassB(x, y);
}
}
精彩评论