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

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

Java factory inheritance with generic interface implementation

问题

我想要一个工厂,它继承另一个工厂,两个工厂都实现相同的通用接口,但具有不同的类型,这些类型彼此继承:

  1. class FactoryA implements FactoryI<A> {
  2. // 共同的代码
  3. ...
  4. A get() {
  5. return new A();
  6. }
  7. }
  8. class FactoryB extends FactoryA implements FactoryI<B> {
  9. B get() {
  10. return new B();
  11. }
  12. }
  13. class B extends A {
  14. }
  15. interface FactoryI<T> {
  16. T get();
  17. }

但是这给我带来了以下编译错误:

"'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:

  1. class FactoryA implements FactoryI&lt;A&gt; {
  2. // common code
  3. ...
  4. A get() {
  5. return new A();
  6. }
  7. }
  8. class FactoryB extends FactoryA implements FactoryI&lt;B&gt; {
  9. B get() {
  10. return new B();
  11. }
  12. }
  13. class B extends A {
  14. }
  15. FactoryI&lt;T&gt; {
  16. T get()
  17. }

But this gives me following compilation error:

  1. &#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

  1. // 你需要将`FactoryA`也改成泛型。这样,子类可以返回`A`的不同子类。
  2. class FactoryA<T extends A> implements FactoryI<T> {
  3. // 公共代码
  4. public T get() {
  5. return (T) new A();
  6. }
  7. }
  8. class FactoryB extends FactoryA<B> {
  9. public B get() {
  10. return new B();
  11. }
  12. }
  13. class A {
  14. }
  15. class B extends A {
  16. }
  17. interface FactoryI<T> {
  18. T get();
  19. }
英文:

You need to make FactoryA generic as well. This way a subclass can return a different subclass of A

  1. class FactoryA&lt;T extends A&gt; implements FactoryI&lt;T&gt; {
  2. // common code
  3. public T get() {
  4. return (T) new A();
  5. }
  6. }
  7. class FactoryB extends FactoryA&lt;B&gt; {
  8. public B get() {
  9. return new B();
  10. }
  11. }
  12. class A {
  13. }
  14. class B extends A {
  15. }
  16. interface FactoryI&lt;T&gt; {
  17. T get();
  18. }

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:

确定