英文:
Java factory inheritance with generic interface implementation
问题
我想要一个工厂,它继承另一个工厂,两个工厂都实现相同的通用接口,但具有不同的类型,这些类型彼此继承:
class FactoryA implements FactoryI<A> {
// 共同的代码
...
A get() {
return new A();
}
}
class FactoryB extends FactoryA implements FactoryI<B> {
B get() {
return new B();
}
}
class B extends A {
}
interface FactoryI<T> {
T get();
}
但是这给我带来了以下编译错误:
"'FactoryI' 无法继承具有不同类型参数的接口:'A' 和 'B'"
我的第一个版本没有让 FactoryB 从 FactoryA 继承,这在之前是可以正常工作的。但是现在两个工厂之间有了共同的代码,我想要重用它们。
实现这一点的最佳方法是什么?
英文:
I would like to have a factory that inherits another one with both factories implementing same generic interface with different type that inherits one another:
class FactoryA implements FactoryI<A> {
// common code
...
A get() {
return new A();
}
}
class FactoryB extends FactoryA implements FactoryI<B> {
B get() {
return new B();
}
}
class B extends A {
}
FactoryI<T> {
T get()
}
But this gives me following compilation error:
'FactoryI' cannot be inherited with different type arguments: 'A' and 'B'
My first version did not have FactoryB inheriting from FactoryA and this was working fine.
But it turns out that there is now common code between both factories that I want to reuse.
What is the best way to achieve this?
答案1
得分: 0
// 你需要将`FactoryA`也改成泛型。这样,子类可以返回`A`的不同子类。
class FactoryA<T extends A> implements FactoryI<T> {
// 公共代码
public T get() {
return (T) new A();
}
}
class FactoryB extends FactoryA<B> {
public B get() {
return new B();
}
}
class A {
}
class B extends A {
}
interface FactoryI<T> {
T get();
}
英文:
You need to make FactoryA
generic as well. This way a subclass can return a different subclass of A
class FactoryA<T extends A> implements FactoryI<T> {
// common code
public T get() {
return (T) new A();
}
}
class FactoryB extends FactoryA<B> {
public B get() {
return new B();
}
}
class A {
}
class B extends A {
}
interface FactoryI<T> {
T get();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论