如果你能跟进,这有点令人费解。我有这个:
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和Interface3将随BaseClass的不同实现而改变。问题出在BaseClass方法2中,因为this
不是Interface2类型,这是它在这种特定情况下所期望的。它编译并运行,但它警告未经检查的电话。
我尝试在基类中实现接口而不是像这样的具体类
abstract public class BaseClass<P extends Interface1, V> implements V
public class Concrete extends BaseClass<Interface3, Interface2>
但Java并不喜欢它。任何想法如何做到这一点?
答案 0 :(得分:1)
解决
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 { }
它编译时没有任何警告,我做的唯一改变是:
abstract class BaseClass<P extends Interface1<Interface2>> implements Interface2
如果您不希望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 { }