简体   繁体   English

抽象类实现了通用的接口类型

[英]Abstract class implement a generic Interface Type

This is a bit convoluted if you can follow along. 如果你能跟进,这有点令人费解。 I have this: 我有这个:

public interface Interface1<T> {
  void method1(T t);
}

public interface Interface2 { }

public interface Interface3 extends Interface1<Interface2> { }

abstract public class BaseClass<P extends Interface1> {
  P p;

  void method2() {
    p.method1(this);
  }
}

public class Concrete extends BaseClass<Interface3> implements Interface2 {
}

Interface2 and Interface3 will change with different implementations of BaseClass. Interface2和Interface3将随BaseClass的不同实现而改变。 The problem is in BaseClass method2 because this is not of type Interface2 which is what it expects in this specific case. 问题出在BaseClass方法2中,因为this不是Interface2类型,它在这种特定情况下是预期的。 It compiles and runs but it warns about an unchecked call. 它编译并运行,但它警告一个未经检查的呼叫。

I tried implementing the interface in the base class instead of the concrete class like this 我尝试在基类中实现接口而不是像这样的具体类

abstract public class BaseClass<P extends Interface1, V> implements V 

public class Concrete extends BaseClass<Interface3, Interface2> 

but Java doesn't like it. 但Java并不喜欢它。 Any ideas how to do this? 任何想法如何做到这一点?

To solve 要解决

interface Interface2 { }

interface Interface1<T> {
  void method1(T t);
}

interface Interface3 extends Interface1<Interface2> { }

abstract  class BaseClass<P extends Interface1<Interface2>> 
     implements Interface2{
  P p;

  void method2() {
    p.method1(this);
  }
}

class Concrete extends BaseClass<Interface3> implements Interface2 { }

It compile without any warning, the only change I made is: 它编译时没有任何警告,我做的唯一改变是:

abstract class BaseClass<P extends Interface1<Interface2>> implements Interface2

If you don't want to BaseClass implements directly Interface2 you can create a "marker": 如果您不希望BaseClass直接实现Interface2,您可以创建一个“标记”:

interface InterfaceFOO {}   // <------------ Marker without methods

interface Interface2 extends InterfaceFOO{ } // <----- harmless extend

interface Interface1<T> {
   void method1(T t);
}

interface Interface3 extends Interface1<InterfaceFOO> { }

abstract  class BaseClass<P extends Interface1<InterfaceFOO>> 
     implements InterfaceFOO{
  P p;

  void method2() {
    p.method1(this);
  }
}

class Concrete extends BaseClass<Interface3> implements Interface2 { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM