[英]Java abstract class Implementing with generics
我有一个带有泛型(T1)的抽象类,该类扩展了我的Filterable接口:
public abstract class AbstractAdapter < T1 extends Filterable, T2 extends AbstractAdapter.Cell > extends ArrayAdapter < T1 > {
public abstract class Cell {
public T1 info;
//...
}
public abstract void setData(T2 cell, int position);
//...
}
我有方法(setData)和Cell类实现的具体类:
public class ConcreteAdapter extends AbstractAdapter < InfoClass, ConcreteAdapter.Cell > {
public class Cell extends AbstractAdapter.Cell {
//...
}
@Override
public void setData(Cell cell, int position) {
InfoClass info = (InfoClass)cell.info; // need to cast from Filterable to InfoClass (why?). Or i have compilation error
}
//...
}
因此,我有ConcreteAdapter类,其中第一个泛型类为InfoClass(扩展了Filterable),在方法setData中,我具有Cell类对象,但是字段“ info”我却视为Filterable,而不是InfoClass。 我认为字段“ info”应该已经是通用类型,因为它声明为
T1信息;
但不是
可过滤的信息;
是否可以在不强制转换的情况下将字段类型从可扩展类更改为泛型类? 还是IDE中的错误?
这是一个非常棘手的情况下,因为AbstractAdapter
是原AbstractAdapter.Cell
。 如果指定了足够的类型,则不再需要强制类型转换:
public abstract class AbstractAdapter < T1 extends Filterable, T2 extends AbstractAdapter<T1, T2>.Cell > extends ArrayAdapter < T1 > {
//...
}
和
public class ConcreteAdapter extends AbstractAdapter < InfoClass, ConcreteAdapter.Cell > {
public class Cell extends AbstractAdapter<InfoClass, ConcreteAdapter.Cell>.Cell {
//...
}
@Override
public void setData(Cell cell, int position) {
InfoClass info = cell.info;
}
//...
}
使它再次工作。 但是,这非常复杂。 如果可能的话,我将把Cell移到顶层课程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.