Sure, here’s the translation: Java工厂继承与泛型接口实现

huangapple go评论70阅读模式
英文:

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&lt;A&gt; {
	// common code
	...
	A get() {
		return new A();
	}
}

class FactoryB extends FactoryA implements FactoryI&lt;B&gt; {
	B get() {
		return new B();
	}
}

class B extends A {
}

FactoryI&lt;T&gt; {
	T get()
}

But this gives me following compilation error:

&#39;FactoryI&#39; cannot be inherited with different type arguments: &#39;A&#39; and &#39;B&#39;

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&lt;T extends A&gt; implements FactoryI&lt;T&gt; {
    // common code
    public T get() {
        return (T) new A();
    }
}

class FactoryB extends FactoryA&lt;B&gt; {
    public B get() {
        return new B();
    }
}

class A {

}

class B extends A {
}

interface FactoryI&lt;T&gt; {
    T get();
}

huangapple
  • 本文由 发表于 2020年10月9日 23:37:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64283086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定